我为JWT令牌生成编写了自定义中间件(基于Asp.Net Core 1.1的一些教程中的代码)。这个中间件使用了一些依赖项: DbContext,UserManager,SignInManager
我正在将我的Asp.Net Core Web API从1.1版升级到2.0版。 在https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x的大部分修改之后 我遇到了这样的错误:
Application startup exception
System.InvalidOperationException: Cannot resolve scoped service 'MyApplicationWebApi.Models.DatabaseContext' from root provider.
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, ServiceProvider serviceProvider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
at Microsoft.Extensions.Internal.ActivatorUtilities.ConstructorMatcher.CreateInstance(IServiceProvider provider)
at Microsoft.Extensions.Internal.ActivatorUtilities.CreateInstance(IServiceProvider provider, Type instanceType, Object[] parameters)
at Microsoft.AspNetCore.Builder.UseMiddlewareExtensions.<>c__DisplayClass4_0.<UseMiddleware>b__0(RequestDelegate next)
at Microsoft.AspNetCore.Builder.Internal.ApplicationBuilder.Build()
at Microsoft.AspNetCore.Hosting.Internal.WebHost.BuildApplication()
我的中间件构造函数如下所示:
#region constructor
public JwtProvider(RequestDelegate next,
IOptions<JwtProviderOptions> options,
DatabaseContext dbContext,
UserManager<ApplicationUser> userManager,
SignInManager<ApplicationUser> signInManager)
{
_next = next;
_options = options.Value;
// Instantiate through Dependency Injection
_dbContext = dbContext;
_userManager = userManager;
_signInManager = signInManager;
}
#endregion
我还看到,在新教程中,ASP.NET 2.0的书籍通常使用一些TokenController端点而不是自定义TokenMiddleware解析JWT令牌生成。我有一个问题:
我应该从使用自定义中间件 JwtProvider 迁移到 JwtProviderController 吗?
我可以将 DbContext,UserManager,SignInManager 注入自定义Middlware吗? (我已经读过构造函数,我只能注入 singleton DI的服务,而进入Invoke()我可以注入范围 DI的服务。这是真的,并且 DbContext,UserManager,SignInManager 此类作用域服务。)
在Program.cs中,我创建了一些范围 host.services.CreateScope()也许我应该在Custom TokenMiddleware中做这样的事情?