Injecting Service in Middleware in ASP.NET Core

后端 未结 3 2048
孤街浪徒
孤街浪徒 2021-02-15 19:50

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:24

    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();
        }
    });
    

提交回复
热议问题