EF7 contructor with MVC6 dependency injection

asp.net-core-mvc c# dependency-injection entity-framework entity-framework-core

Question

Testing out the new MVC6 and EF7 framework.

We often need the HttpContext in our database layers. To do this in MVC6 we simply have a DbContext constructor that looks like this:

 public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
    {                  
        HttpContext _httpContext;                     
        public ApplicationUser CurrentUser { get; set; }                

        public ApplicationDbContext(IHttpContextAccessor httpContextFactory=null)

and in our Startup.cs we register our DI as so:

services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();

This works perfect...

...until it doesn't. When running the application, all is well and good. However, when I need to apply some model changes using "dnx . ef migration add" we get an error "No parameterless constructor defined for this object."

Ok, no problem. So we add an additional constructur with no parameters, which we want to only be used by the migration process. However, DI process registers the parameterless constructor only so the HttpContext object is never passed in.

So how do I get MVC's default DI model to forcefully use my constructor with the parameter? and keep the parameterless constructor for migrations?

Popular Answer

Specifying which constructor to call when the class is registered is not supported by the basic ASP.NET out-of-the-box DI (it only resolves types with one public constructor).

You could use more advanced DI for this purpose - i.e. there is an alpha2 version of autofac available for ASP.NET 5 ("Autofac": "4.0.0.0-alpha2", "Autofac.Dnx": "4.0.0-alpha1").



Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why