Injecting Service in Middleware in ASP.NET Core

后端 未结 3 2058
孤街浪徒
孤街浪徒 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:22

    There is no easy or clean way to do this. You can't modify the IServiceCollection outside of the ConfigureServices method. But even if you could, it's of no use, because the container has already been built before Configure is being called.

    What you could do is create a factory class and register it as scoped.

    public interface IDataProviderFactory
    {
        bool UseInMemoryProvider { get; set; }
        IDataProvider Create();
    }
    
    public class DataProviderFactory : IDataProviderFactory
    {
        private readonly IServiceProvider provider;
    
        public bool UseInMemoryProvider { get; set; }
    
        public DataProviderFactory(IServiceProvider provider) 
        {
            this.provider = provider;
        }
    
        public IDataProvider Create()
        {
            if(UseInMemoryProvider) 
            {
                return provider.RequestService<InMemoryDataProvider>();
            }
    
            return provider.RequestService<DbDataProvider>();
        }
    }
    

    Then in your middleware:

    public class MyMiddleware
    {
        public void Invoke(HttpContext context) 
        {
            var dataProviderFactory = context.RequestServices.RequestService<IDataProviderFactory>();
    
            // Your logic here
            if(...)
            {
                dataProviderFactory.UseInMemoryStore = true;
            } 
        }
    }
    

    and in your controller/services:

    public class MyController : Controller 
    {
        private readonly IDataProvider dataProvider;
    
        public MyController(IDataProviderFactory dataProviderFactory)
        {
            dataProvider = dataProviderFactory.Create();
        }
    }
    
    0 讨论(0)
  • 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<DbDataProvider>();
    services.AddScoped<InMemDataProvider>();
    services.AddScoped<IDataProvider>(ctx =>
    {
        var contextAccessor = ctx.GetService<IHttpContextAccessor>();
        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<InMemDataProvider>();
        }
        else
        {
            return ctx.GetService<DbDataProvider>();
        }
    });
    
    0 讨论(0)
  • 2021-02-15 20:26

    The answer above from Tsen is correct. You should implement a factory.

    But in addition you can also register factory methods to the services collection. Like so:

    Services.AddTransient(serviceProvider => serviceProvider.GetService<IDataProviderFactory>().Create())
    

    This registers your IDataProvider. In the Create you should evaluate that HTTP header value so it returns the correct IDataProvider instance. Then in any class you need it you can simply request IDataProvider via the constructor and the correct implementation will be provided by the container.

    0 讨论(0)
提交回复
热议问题