【问题标题】:Change DbContext in ASP.NET Middleware在 ASP.NET 中间件中更改 DbContext
【发布时间】:2021-08-31 04:11:13
【问题描述】:
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?

【问题讨论】:

  • 来自 Timur Umerov:您是否需要根据请求中的某些数据创建具有特定连接字符串的 DbContext?我理解正确吗?
  • @PanagiotisKanavos 是的
  • 但你为什么要这样做?
  • @davidfowl 多租户软件

标签: c# entity-framework asp.net-core dependency-injection


【解决方案1】:

您必须像这样在ConfigureServices 中注册您的DbContext

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() 才能正常工作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-02
    • 1970-01-01
    • 2020-02-02
    • 2012-09-04
    • 2018-02-19
    • 1970-01-01
    相关资源
    最近更新 更多