IServiceProvider in ASP.NET Core

后端 未结 7 1823
被撕碎了的回忆
被撕碎了的回忆 2021-02-02 08:02

I starting to learn changes in ASP.NET 5(vNext) and cannot find how to get IServiceProvider, for example in \"Model\"\'s method

public class Entity 
{
     publ         


        
7条回答
  •  再見小時候
    2021-02-02 08:30

    Generally you want to have the DI do its thing and inject that for you:

    public class Entity 
    {
        private readonly IDataContext dbContext;
    
        // The DI will auto inject this for you
        public class Entity(IDataContext dbContext)
        {
            this.dbContext = dbContext;
        }
    
         public void DoSomething()
         {
             // dbContext is already populated for you
             var something = dbContext.Somethings.First();
         }
    }
    

    However, Entity would have to be automatically instantiated for you... like a Controller or a ViewComponent. If you need to manually instantiate this from a place where this dbContext is not available to you, then you can do this:

    using Microsoft.Extensions.PlatformAbstractions;
    
    public class Entity 
    {
        private readonly IDataContext dbContext;
    
        public class Entity()
        {
            this.dbContext = (IDataContext)CallContextServiceLocator.Locator.ServiceProvider
                                .GetService(typeof(IDataContext));
        }
    
         public void DoSomething()
         {
             var something = dbContext.Somethings.First();
         }
    }
    

    But just to emphasize, this is considered an anti-pattern and should be avoided unless absolutely necessary. And... at the risk of making some pattern people really upset... if all else fails, you can add a static IContainer in a helper class or something and assign it in your StartUp class in the ConfigureServices method: MyHelper.DIContainer = builder.Build(); And this is a really ugly way to do it, but sometimes you just need to get it working.

提交回复
热议问题