Startup.Auth.cs //I have added my DbContext here
// Configure the db context, user manager and signin manager to use a single instance per request
app.CreatePerOwinContext(ProjectPlannerContext.Create);
app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
In the AccountController.cs I want to create an instance of service which needs UnitOfWork instance to do Database related stuff. So here is the code:
public AccountController()
{
contactManager = new ContactManager(UnitOfWork);
}
where the UnitOfWork is a property defined like this:
public UnitOfWork UnitOfWork
{
get
{
if (unitOfWork == null)
{
//Here the HttpContext is NULL
unitOfWork = new UnitOfWork(HttpContext.GetOwinContext().Get<ProjectPlannerContext>());
}
return unitOfWork;
}
}
I have a global Authorization filter applied, so when I run the application the first thing to do is to Login to the website(this will cause a request to AccountController's login method - and gives an error Object reference not set to an instance, because of the call to UnitOfWork in controllers constructor).
The strange thing for me is that if I comment the contactManager line in the constructor, upon Login Asp.NET MVC Uses a SignInManager defined like this:
public ApplicationSignInManager SignInManager
{
get
{
return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
}
private set
{
_signInManager = value;
}
}
And this works perfectly, I can register (Object reference error not thrown here) and see that in the Database my User is inserted. So my question is why this happens, and how to initialize my Service if not in the constructor?
Actually there is workaround if I define the UnitOfWork like:
public UnitOfWork UnitOfWork
{
get
{
if (unitOfWork == null)
{
unitOfWork = new UnitOfWork(ProjectPlannerContext.Create());
}
return unitOfWork;
}
}
But this means that I should Create database context in every Controller..
What is the best practice/solution to that?