IServiceProvider in ASP.NET Core

后端 未结 7 1814
被撕碎了的回忆
被撕碎了的回忆 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:31

    Instead of getting your service inline, try injecting it into the constructor.

    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddTransient(typeof(DataContext));
        }
    }
    
    public class Entity
    {
        private DataContext _context;
    
        public Entity(DataContext context)
        {
            _context = context;
        }
    
        public void DoSomething()
        {
            // use _context here
        }
    }
    

    I also suggest reading up on what AddTransient means, as it will have a significant impact on how your application shares instances of DbContext. This is a pattern called Dependency Injection. It takes a while to get used to, but you will never want to go back once you do.

提交回复
热议问题