【问题标题】:Getting InvalidOperationException when trying to inject db context into custom middleware尝试将数据库上下文注入自定义中间件时出现 InvalidOperationException
【发布时间】:2018-01-30 21:57:45
【问题描述】:

我需要将一个 db 上下文对象注入一个名为 AuthenticateClient 的自定义中间件,但我得到了异常:

InvalidOperationException:无法解析范围服务 来自根提供商的“LC.Tools.API.Data.ApiDbContext”。

AuthenticateClient.cs

public class AuthenticateClient
{
    private readonly RequestDelegate _next;
    private readonly ILogger _logger;
    private readonly GenericUnitOfWork _worker;

    public AuthenticateClient(RequestDelegate next, ApiDbContext db, IHttpContextAccessor httpContext, IHostingEnvironment env, ILoggerFactory loggerFactory, IOptions<Utility.LCLog.Settings> settings)
    {
        _next = next;
        _logger = loggerFactory.CreateLogger(settings.Value.ApplicationName);
        _worker = new GenericUnitOfWork(new AppHelper(httpContext, db, env));
    }

    public async Task Invoke(HttpContext context)
    {
        if (!context.Request.Headers.Keys.Contains("key") || !context.Request.Headers.Keys.Contains("pass"))
        {
            context.Response.StatusCode = 400;
            await context.Response.WriteAsync("Key or Pass missing from request header values");

            return;
        }
        else
        {
            Client client;
            string key, pass;

            key = context.Request.Headers["key"];
            pass = context.Request.Headers["pass"];

            client = await _worker.GetRepo<Client>().SingleOrDefault(clnt => clnt.Active && clnt.Key.Equals(key) && clnt.Password.Equals(pass));

            if (client == null)
            {
                _logger.LogWarning("Client authentication failed", new string[] { "Key: " + key, "Password: " + pass, "Host: " + context.Request.Host });

                context.Response.StatusCode = 401;
                await context.Response.WriteAsync("Authentication failed");

                return;
            }
        }

        await _next.Invoke(context);
    }
}

AuthenticateClientExtension.cs

public static class AuthenticateClientExtension
{
    public static IApplicationBuilder UseClientAuthentication(this IApplicationBuilder builder)
    {
        return builder.UseMiddleware<AuthenticateClient>();
    }
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApiDbContext>(options => options.UseSqlServer(this.ConnectionString));

    services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();

    services.AddMvc();
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IOptions<Settings> lclog)
{
    loggerFactory.AddLCLog(lclog.Value);

    app.UseClientAuthentication();
    app.UseMvc();
}

ApiDbContext.cs

public class ApiDbContext : DbContext, IApiDbContext
{
    public ApiDbContext(DbContextOptions<ApiDbContext> options) : base(options) { }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        ...
    }
}

【问题讨论】:

  • ApiDbContext 类是什么样的?有依赖吗?
  • 问题使用 ApiDbContext 类更新
  • 什么是AddEntityFrameworkSqlServer?没有它,你的应用还能运行吗?
  • 我不知道如何以任何其他方式设置数据库上下文
  • 我已经更改了注册 ApiDbContext 的方式,但仍然出现同样的错误

标签: c# asp.net-core asp.net-core-mvc


【解决方案1】:

解决方案是使用 IApplicationBuilder 创建范围和初始化 ApiDbContext 并将其传递给中间件对象。我还更改了注册 ApiDbContext

的方式

AuthenticateClientExtension.cs

public static class AuthenticateClientExtension
{
    public static IApplicationBuilder UseClientAuthentication(this IApplicationBuilder builder)
    {
        var scope = builder.ApplicationServices.CreateScope();
        ApiDbContext db = scope.ServiceProvider.GetRequiredService<ApiDbContext>();

        return builder.UseMiddleware<AuthenticateClient>(db);
    }
}

Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApiDbContext>(options => options.UseSqlServer(this.ConnectionString));

    ...
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IOptions<Settings> lclog)
{
    ...

    app.UseClientAuthentication();
    app.UseMvc();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-01
    • 2021-12-04
    • 2018-01-16
    • 2020-11-15
    • 2021-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多