【问题标题】:How can you add a Microsoft Graph client service as a MediatR service in .NET Core 3.1?如何在 .NET Core 3.1 中将 Microsoft Graph 客户端服务添加为 MediatR 服务?
【发布时间】:2020-11-20 17:22:08
【问题描述】:

所以我有一个带有自己的本地数据上下文的 .NET Core 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();
            });
        }
    }
}

还有我用于调用下游的应用程序处理程序:

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;
            }
        }
    }
}

希望我在这里是正确的,但如果我不是,请告诉我。

【问题讨论】:

  • 希望您为上述 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,因为我不再使用它了。问题仍然存在。
  • 你试过了。作为接下来的步骤,我将开始一个接一个地隔离包并添加回来查看,编译以查看我在哪一点看到错误。这将帮助您消除您使用的库的问题。此外,我会看到任何有关确切组合的参考文档,以查看是否也报告了任何已知问题。
  • 你知道我得到的错误是什么意思吗?

标签: .net-core azure-active-directory microsoft-graph-api mediator mediatr


【解决方案1】:

是的,这是我的一个简单的疏忽。

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

services.AddMicrosoftIdentityWebApiAuthentication(Configuration)
.EnableTokenAcquisitionToCallDownstreamApi()
.AddMicrosoftGraph(Configuration.GetSection("DownstreamApi"))
.AddInMemoryTokenCaches();

将以下内容添加到 appsettings(范围可能不同):

  "DownstreamAPI": {
    "BaseUrl": "https://graph.microsoft.com/v1.0",
    "Scopes": "user.read"
  },

并且一定要安装Microsoft.Identity.Web.MicrosoftGraph以启用AddMicrosoftGraph()功能。

【讨论】:

    猜你喜欢
    • 2014-04-04
    • 1970-01-01
    • 2020-07-31
    • 2014-03-18
    • 1970-01-01
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多