【问题标题】:Cannot resolve scoped service dbcontext from root provider [duplicate]无法从根提供程序解析范围服务 dbcontext [重复]
【发布时间】:2020-08-01 16:43:37
【问题描述】:

我创建了一个 API 日志中间件来记录对 DB 和 Azure Microsoft 洞察力的请求,但是由于某种原因,找不到数据库上下文的依赖注入(导致无法从根提供程序解析范围服务)。

API 记录中间件

public class APILoggingMiddleware
{
    private readonly TelemetryClient _telemetry;

    private readonly ILogger _logger;

    private readonly RequestDelegate _next;

    private APIsAuditContext db;

    public static IConfiguration _configuration;
    public APILoggingMiddleware(RequestDelegate next, ILoggerFactory loggerFactory, TelemetryClient telemetry, IConfiguration configuration, APIsAuditContext dbContext)
    {
        _configuration = configuration;

        _telemetry = telemetry;

        _next = next;

        _logger = loggerFactory.CreateLogger<APILoggingMiddleware>();

        db = dbContext;
    }

    //static class to simplify adding the middleware to the application’s pipeline

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

            Task logReq = logRequest(context);
            Task lodRes = logResponse(context);
        }
     }
  }

数据库上下文

public class APIsAuditContext : DbContext
{
    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        if (!optionsBuilder.IsConfigured)
        {
        }
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
    }
    public APIsAuditContext(DbContextOptions<APIsAuditContext> options) : base(options) { }
    public DbSet<APIsRequestsAudit> APIsRequestsAudits { get; set; }


}

启动

 public class Startup
{
    public IConfiguration _configuration { get; }

    public Startup(IConfiguration configuration)
    {
        _configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {

        services.AddDbContext<APIsAuditContext>(options => options.UseSqlServer(_configuration["ConnectionStrings:APIAuditConnection"]));

        services.AddApplicationInsightsTelemetry();
        services.AddControllers();
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {

        //Pipeline to API Logging 
        app.UseRequestResponseLogging();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseHttpsRedirection();
        app.UseRouting();
        app.UseAuthorization();

        app.UseEndpoints(endpoints => 
        {
            endpoints.MapControllers();
        });



    }
}

有人可以帮忙吗?

【问题讨论】:

标签: asp.net-core asp.net-core-3.1


【解决方案1】:

根据https://docs.microsoft.com/en-us/aspnet/core/fundamentals/middleware/write?view=aspnetcore-3.1#per-request-middleware-dependencies,您必须在 Invoke 方法中注入作用域服务:

public class CustomMiddleware
{
    private readonly RequestDelegate _next;

    public CustomMiddleware(RequestDelegate next)
    {
        _next = next;
    }

    // IMyScopedService is injected into Invoke
    public async Task Invoke(HttpContext httpContext, IMyScopedService svc)
    {
        svc.MyProperty = 1000;
        await _next(httpContext);
    }
}

【讨论】:

  • @Brian(也许指出了显而易见的),在你的情况下,IMyScopedServiceAPIsAuditContext dbContext,或者,更好的选择,IAPIsAuditContext(你可以直接注入它,没有接口,但它是一个不好的做法)。
猜你喜欢
  • 2018-04-04
  • 1970-01-01
  • 2020-05-22
  • 2020-09-06
  • 2020-05-11
  • 1970-01-01
  • 2020-02-22
  • 1970-01-01
  • 2022-10-18
相关资源
最近更新 更多