首页 > 解决方案 > 在 ASP.NET 中间件中更改 DbContext

问题描述

public class RequestCultureMiddleware
    {
        private readonly RequestDelegate _next;

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

        public async Task InvokeAsync(HttpContext context)
        {
            var cultureQuery = context.Request.Query["culture"];
            if (!string.IsNullOrWhiteSpace(cultureQuery))
            {
                var culture = new CultureInfo(cultureQuery);

                CultureInfo.CurrentCulture = culture;
                CultureInfo.CurrentUICulture = culture;

            }

            // Call the next delegate/middleware in the pipeline
            await _next(context);
        }

在此示例中,实现了自定义中间件。我想根据我在这个中间件中所做的事情来更改 DbContext。我可以添加一个将被注入的 DbContext 参数,然后用它做我需要做的事情:

public async Task InvokeAsync(HttpContext context, MyDbContext context)
{
    context.Database.GetDbConnection().ConnectionString = "..."; // +
    var cultureQuery = context.Request.Query["culture"];
    if (!string.IsNullOrWhiteSpace(cultureQuery))
    {
        var culture = new CultureInfo(cultureQuery);

        CultureInfo.CurrentCulture = culture;
        CultureInfo.CurrentUICulture = culture;

    }

    // Call the next delegate/middleware in the pipeline
    await _next(context);
}

但是,我将如何传播新的 DbContext?

标签: c#entity-frameworkasp.net-coredependency-injection

解决方案


您必须像这样注册您DbContextConfigureServices

services.AddScoped<MyDbContext>(sp=> {
   var httpContextAccessor = sp.GetRequiredService<IHttpContextAccessor>();
   var httpContext = httpContextAccessor.HttpContext;
   
   var request = httpContext.Request;
   // form your connection string here based on data
   // from the request and pass it down to DbContext constructor
   var connString = "..."; 
   return new MyDbContext(connString);
});

您还必须添加services.AddHttpContextAccessor()它才能正常工作。


推荐阅读