Asp.Net Core 2.0
我编写了用于JWT令牌生成的定制中间件(基于来自Asp.Net Core 1.1的一些教程的代码)该中间件使用了一些依赖关系: DbContext,UserManager,SignInManager
我正在将我的Asp.Net Core Web API从1.1升级到ASP.NET的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的书籍JWT令牌生成通常使用一些TokenController端点而不是自定义的TokenMiddleware来解决。 我有一个问题:
我应该从使用自定义中间件JwtProvider迁移到JwtProviderController吗?
我可以将DbContext,UserManager,SignInManager注入到自定义的Middware中吗? (我已经读到构造函数中,我只能注入单例 DI的服务,并且注入Invoke()我可以注入作用域 DI的服务。这是真的,并且是DbContext,UserManager,SignInManager等范围的服务。)
在Program.cs中,我使用host.services.CreateScope()创建了一些范围,也许我应该在Custom TokenMiddleware中做这样的事情?
上一篇: Asp.Net Core 2.0