Is it “safe” to cache IServiceProvider for an app's lifetime?

后端 未结 2 1664
余生分开走
余生分开走 2021-01-16 09:08

I\'m using ASP.NET Core, and its builtin DI container. I\'m using a third-party library (NLog) which I can\'t change.

My Foo class has a dependency (by

2条回答
  •  长发绾君心
    2021-01-16 09:28

    You don't want to inject your IoC container anywhere. That's a bad practice that allows for sloppy coding, and makes unit testing harder, amongst many other reasons.

    Instead introduce a factory that can be injected and create a context on demand:

    public interface IDbContextFactory
    {
        TContext Create();
    }
    
    public class DbContextFactory : IDbContextFactory
        where TContext : DbContext
    {
        private readonly Func _contextCreator;
    
        public DbContextFactory(Func contextCreator)
        {
            _contextCreator = contextCreator;
        }
    
        public TContext Create()
        {
            return _contextCreator();
        }
    }
    

    Now if you inject this into your Foo:

    public class Foo 
    {
        private readonly IDbContextFactory _contextFactory;
        public Foo(IDbContextFactory contextFactory)
        { 
            _contextFactory = contextFactory;
        }
    
        public void bar() {
        {
            using (var context = _contextFactory.Create())
            {
                // use your freshly instantiated context
            }
        }
    }
    

    Any decent dependency injection framework can resolve the Func parameter of the DbContextFactory, and pass a func there that creates an instance per request.

提交回复
热议问题