How to use Dependency Injection with Entity Framework DbContext?

后端 未结 1 1217
执笔经年
执笔经年 2020-12-19 06:34

I am currently working on including a new functionality for a Website.

I have a DbContext class which I created using EF6.

The website uses a Master Layout i

1条回答
  •  执笔经年
    2020-12-19 06:56

    I am prefer SimpleInjector but it wont differ that much for any other IoC container.

    More info here

    Example for ASP.Net4:

    // You'll need to include the following namespaces
    using System.Web.Mvc;
    using SimpleInjector;
    using SimpleInjector.Integration.Web;
    using SimpleInjector.Integration.Web.Mvc;
    
        // This is the Application_Start event from the Global.asax file.
        protected void Application_Start()
        {
            // Create the container as usual.
            var container = new Container();
            container.Options.DefaultScopedLifestyle = new WebRequestLifestyle();
    
            // Register your types, for instance:
            container.Register(Lifestyle.Scoped);
    
            // This is an extension method from the integration package.
            container.RegisterMvcControllers(Assembly.GetExecutingAssembly());
    
            // This is an extension method from the integration package as well.
            container.RegisterMvcIntegratedFilterProvider();
    
            container.Verify();
    
            DependencyResolver.SetResolver(new SimpleInjectorDependencyResolver(container));
        }
    

    Such registration will create DbContext per every WebRequest and close it for you. So you simply need inject IDbContext in your controller and use it as usual without using:

    public class HomeController : Controller
    {
        private readonly IDbContext _context;
    
        public HomeController(IDbContext context)
        {
            _context = context;
        }
    
        public ActionResult Index()
        {
            var data = _context.GetData();
            return View(data);
        }
    }
    

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