gpt4 book ai didi

c# - asp.net core中间件如何做DI?

转载 作者:IT王子 更新时间:2023-10-29 04:41:41 26 4
gpt4 key购买 nike

我正在尝试将依赖注入(inject)到我的中间件构造函数中,如下所示

public class CreateCompanyMiddleware
{
private readonly RequestDelegate _next;
private readonly UserManager<ApplicationUser> _userManager;

public CreateCompanyMiddleware(RequestDelegate next
, UserManager<ApplicationUser> userManager
)
{
_next = next;
}

public async Task Invoke(HttpContext context)
{
await _next.Invoke(context);
}
}

我的 Startup.cs 文件看起来像

public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(options =>
options.UseMySql(Configuration.GetConnectionString("IdentityConnection")));

services.AddIdentity<ApplicationUser, IdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
...

app.UseMiddleware<CreateCompanyMiddleware>();

...

但是我收到了这个错误

An error occurred while starting the application. InvalidOperationException: Cannot resolve scoped service 'Microsoft.AspNetCore.Identity.UserManager`1[Common.Models.ApplicationUser]' from root provider. Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteValidator.ValidateResolution(Type serviceType, IServiceScope scope, IServiceScope rootScope)

最佳答案

UserManager<ApplicationUser>是(默认情况下)注册为一个作用域依赖,而你的CreateCompanyMiddleware中间件在应用程序启动时构建(有效地使其成为单例)。这是一个相当标准的错误,表示您不能将作用域 依赖项带入单例 类。

在这种情况下修复很简单——你可以注入(inject) UserManager<ApplicationUser>进入你的Invoke方法:

public async Task Invoke(HttpContext context, UserManager<ApplicationUser> userManager)
{
await _next.Invoke(context);
}

这记录在 ASP.NET Core Middleware: Per-request middleware dependencies 中:

Because middleware is constructed at app startup, not per-request, scoped lifetime services used by middleware constructors aren't shared with other dependency-injected types during each request. If you must share a scoped service between your middleware and other types, add these services to the Invoke method's signature. The Invoke method can accept additional parameters that are populated by DI:

关于c# - asp.net core中间件如何做DI?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52204022/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com