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?
We often need the HttpContext in our database layers.. as Mr Mackey from South Park would say: "this is bad, mkay?" :) - Jeff