EF7 contructor with MVC6 dependency injection

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


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?

2/8/2019 10:52:05 AM

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": "", "Autofac.Dnx": "4.0.0-alpha1").

10/11/2015 6:45:21 PM

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow