.net core 如何将Microsoft Graph客户端服务添加为.NET Core 3.1中的MediatR服务?

.net core 如何将Microsoft Graph客户端服务添加为.NET Core 3.1中的MediatR服务?,.net-core,azure-active-directory,microsoft-graph-api,mediator,mediatr,.net Core,Azure Active Directory,Microsoft Graph Api,Mediator,Mediatr,因此,我有一个.NET核心web API,它有自己的本地数据上下文,我想添加调用Microsoft Graph作为下游API的功能 但是,当我尝试添加必要的属性来调用Graph API时,我得到一个生成错误: Unhandled exception. System.AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'Serv

因此,我有一个.NET核心web API,它有自己的本地数据上下文,我想添加调用Microsoft Graph作为下游API的功能

但是,当我尝试添加必要的属性来调用Graph API时,我得到一个生成错误:

Unhandled exception. System.AggregateException: Some services are not able to be constructed (Error while validating the service descriptor 'ServiceType: MediatR.IRequestHandler`2[Application.Users.Me+Query,Microsoft.Graph.User] Lifetime: Transient ImplementationType: Application.Users.Me+Handler': Unable to resolve service for type 'Microsoft.Graph.GraphServiceClient' while attempting to activate 'Application.Users.Me+Handler'.)
这是我的创业课程:

using API.Middleware;
using Application.TestEntities;
using FluentValidation.AspNetCore;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Authorization;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Persistence;
using Microsoft.Identity.Web;

namespace API
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<DataContext>(opt =>
            {
                opt.UseSqlite(Configuration.GetConnectionString("DefaultConnection"));
            });
            services.AddCors(opt =>
            {
                opt.AddPolicy("CorsPolicy", policy =>
                {
                    policy.AllowAnyHeader().AllowAnyMethod().WithOrigins("http://localhost:3000");
                });
            });

            services.AddMicrosoftIdentityWebApiAuthentication(Configuration)
                .EnableTokenAcquisitionToCallDownstreamApi()
                .AddInMemoryTokenCaches();

            services.AddMediatR(typeof(List.Handler).Assembly);
            services.AddControllers(opt =>
            {
                var policy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
                opt.Filters.Add(new AuthorizeFilter(policy));
            })
            .AddFluentValidation(cfg => cfg.RegisterValidatorsFromAssemblyContaining<Create>());
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            app.UseMiddleware<ErrorHandlingMiddleware>();
            if (env.IsDevelopment())
            {
                // app.UseDeveloperExceptionPage();
            }

            app.UseCors("CorsPolicy");

            app.UseRouting();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}
使用API.Middleware;
使用应用程序测试;
使用FluentValidation.AspNetCore;
使用MediatR;
使用Microsoft.AspNetCore.Authorization;
使用Microsoft.AspNetCore.Builder;
使用Microsoft.AspNetCore.Hosting;
使用Microsoft.AspNetCore.Mvc.Authorization;
使用Microsoft.EntityFrameworkCore;
使用Microsoft.Extensions.Configuration;
使用Microsoft.Extensions.DependencyInjection;
使用Microsoft.Extensions.Hosting;
使用持久性;
使用Microsoft.Identity.Web;
名称空间API
{
公营创业
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
services.AddDbContext(opt=>
{
opt.UseSqlite(Configuration.GetConnectionString(“DefaultConnection”);
});
services.AddCors(opt=>
{
opt.AddPolicy(“CorsPolicy”,policy=>
{
policy.AllowAnyHeader().AllowAnyMethod().WithOrigins(“http://localhost:3000");
});
});
services.addMicrosoftIdentityWebAPI身份验证(配置)
.EnableTokenAcquisitionTollDownstreamMapi()
.AddInMemoryTokenCaches();
AddMediatR(typeof(List.Handler).Assembly);
services.AddControllers(opt=>
{
var policy=new AuthorizationPolicyBuilder().RequireAuthenticatedUser().Build();
添加(新的授权过滤器(策略));
})
.AddFluentValidation(cfg=>cfg.RegisterValidatorsFromAssemblyContaining());
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境)
{
app.UseMiddleware();
if(env.IsDevelopment())
{
//app.UseDeveloperExceptionPage();
}
附录UseCors(“公司政策”);
app.UseRouting();
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(端点=>
{
endpoints.MapControllers();
});
}
}
}
以及用于调用下游的应用程序处理程序:

using System.Threading;
using System.Threading.Tasks;
using MediatR;
using Microsoft.Graph;
using Microsoft.Identity.Web;

namespace Application.Users
{
    public class Me
    {
        public class Query : IRequest<User> { }

        public class Handler : IRequestHandler<Query, User>
        {
            private readonly ITokenAcquisition _tokenAcquisition;
            private readonly GraphServiceClient _graphServiceClient;
            public Handler(ITokenAcquisition tokenAcquisition, GraphServiceClient graphServiceClient)
            {
                _tokenAcquisition = tokenAcquisition;
                _graphServiceClient = graphServiceClient;
            }

            public async Task<User> Handle(Query request, CancellationToken cancellationToken)
            {
                var user = await _graphServiceClient.Me.Request().GetAsync();
                return user;
            }
        }
    }
}
使用系统线程;
使用System.Threading.Tasks;
使用MediatR;
使用Microsoft.Graph;
使用Microsoft.Identity.Web;
命名空间应用程序。用户
{
公开课我
{
公共类查询:IRequest{}
公共类处理程序:IRequestHandler
{
私有只读ITokenAcquisition(令牌收购);
专用只读GraphServiceClient(GraphServiceClient);
公共处理程序(ITokenAcquisition tokenAcquisition,GraphServiceClient GraphServiceClient)
{
_tokenAcquisition=tokenAcquisition;
_graphServiceClient=graphServiceClient;
}
公共异步任务句柄(查询请求、CancellationToken CancellationToken)
{
var user=await_graphServiceClient.Me.Request().GetAsync();
返回用户;
}
}
}
}

希望我在这方面走对了,但如果我没有,请告诉我。

对,所以这只是我的一个简单疏忽

根据@franklores,您需要在启动类服务中注册Microsoft Graph:

services.AddMicrosoftIdentityWebApiAuthentication(Configuration)
.EnableTokenAcquisitionToCallDownstreamApi()
.AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
.AddInMemoryTokenCaches();
将以下内容添加到appsettings(范围可能不同):


请务必安装
Microsoft.Identity.Web.MicrosoftGraph
以启用
AddMicrosoftGraph()
功能。

正确,因此这是我的一个简单疏忽

根据@franklores,您需要在启动类服务中注册Microsoft Graph:

services.AddMicrosoftIdentityWebApiAuthentication(Configuration)
.EnableTokenAcquisitionToCallDownstreamApi()
.AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
.AddInMemoryTokenCaches();
将以下内容添加到appsettings(范围可能不同):


请务必安装
Microsoft.Identity.Web.MicrosoftGraph
以启用
AddMicrosoftGraph()
功能。

希望您在上述SDK中使用的是最新的NuGet软件包,对吗?我相信大多数情况下都是这样。。用于我的API项目(启动)我有:
Microsoft.EntityFrameworkCore.Design-3.1.10 Newtonsoft.Json-12.0.3 Microsoft.Identity.Web-1.3.0
我有:
MediatR.Extensions.Microsoft.DependencyInjection-8.1.0 FluentValidation.AspNetCore-9.2.0 Microsoft.Graph-3.20.0 Microsoft.Identity.Web-1.3.0
刚刚升级了我的所有软件包,并且去掉了Newtonsoft.Json,因为我不再使用它了。问题依然存在。很好,您尝试了。作为下一步,我将开始一个接一个地隔离包,并添加回see、compile以查看在哪一点我看到了错误。这将帮助您消除所使用库的问题。此外,我会看到任何关于确切组合的参考文档,以查看是否也报告了任何已知问题。您知道我收到的错误是什么意思吗?希望您对上述SDK使用最新的NuGet软件包,对吗?我相信是的,大部分情况下。。对于我的API项目(启动),我有:
Microsoft.EntityFrameworkCore.Design-3.1.10 Newtonsoft.Json-12.0.3 Microsoft.Identity.Web-1.3.0
对于应用程序,我有:
MediatR.Extensions.Microsoft.DependencyInjection-8.1.0 FluentValidation.AspNetCore-9.2.0 Microsoft.Graph-3.20.0