EF7 Contractor with MVC6 Dependency Injection

Testing the new MVC6 and EF7 framework.

We often need 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 like this:

services.AddTransient<IHttpContextAccessor, HttpContextAccessor>();

This works great ...

... until that happens. When you start the application, everything is fine and good. However, when I need to apply some changes to the model with "dnx. Ef migration add", we get the error "No parameterless constructor for this object".

OK, no problem. Therefore, we add an additional parameterless constructor that we only want to use during the migration process. However, the DI process registers a parameterless constructor, so the HttpContext object is never passed.

So how do I get the default MVC DI model for strong use of my parameterized constructor? and keep the construction without parameters for migration?

+3


source to share


1 answer


Specifying which constructor to call when a class is registered is not supported by ASP.NET core digital DI code (it only allows types with one public constructor).



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

0


source







All Articles