Asp.Net Core 2.0
I have written custom middleware for JWT Token generation (based on code from some tutorials for Asp.Net Core 1.1) This middleware uses some dependencies: DbContext, UserManager, SignInManager
I am upgrading my Asp.Net Core Web API from 1.1 to 2.0 version of ASP.NET. And after most of the modifications from https://docs.microsoft.com/en-us/aspnet/core/migration/1x-to-2x/identity-2x I have encountered such an error:
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()
My Middleware constructor looks like this:
#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
I have also seen that in new tutorials, books for ASP.NET 2.0 the JWT token generation is usually resolved using some TokenController endpoint rather then custom TokenMiddleware. And I have a question:
Should I migrate from using custom middleware JwtProvider to JwtProviderController ?
Can I inject DbContext, UserManager, SignInManager into custom Middlware? (I have read that into constructor I can only inject singleton DI's services, and into Invoke() I can inject scoped DI's services. Is that true, and are DbContext, UserManager, SignInManager such scoped services.)
In Program.cs I have created some scope using host.services.CreateScope() maybe I should make something like this in Custom TokenMiddleware?
上一篇: 值类型的依赖注入
下一篇: Asp.Net Core 2.0