Injecting Service in Middleware in ASP.NET Core

后端 未结 3 2047
孤街浪徒
孤街浪徒 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();
            }
    
            return provider.RequestService();
        }
    }
    

    Then in your middleware:

    public class MyMiddleware
    {
        public void Invoke(HttpContext context) 
        {
            var dataProviderFactory = context.RequestServices.RequestService();
    
            // 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();
        }
    }
    

提交回复
热议问题