Injecting Service in Middleware in ASP.NET Core

后端 未结 3 1121
别跟我提以往
别跟我提以往 2021-02-15 19:57

I want to inject a service based on the HTTP header value. So I have 2 classes - DbDataProvider and InMemDataProvider, both are implemented from IDataProvider. Whenever an API

3条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-15 20:31

    You can achieve this in your DI config in Startup.cs.

    They key is services.AddHttpContextAccessor() which allows you to get access to the HttpContext.

    services.AddHttpContextAccessor();
    
    services.AddScoped();
    services.AddScoped();
    services.AddScoped(ctx =>
    {
        var contextAccessor = ctx.GetService();
        var httpContext = contextAccessor.HttpContext;
    
        // Whatever the header is that you are looking for
        if (httpContext.Request.Headers.TryGetValue("Synthetic", out var syth))
        {
            return ctx.GetService();
        }
        else
        {
            return ctx.GetService();
        }
    });
    

提交回复
热议问题