简体   繁体   中英

EF7 constructor with MVC6 dependency injection

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?

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 - ie there is an alpha2 version of autofac available for ASP.NET 5 ("Autofac": "4.0.0.0-alpha2", "Autofac.Dnx": "4.0.0-alpha1").

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM