In my MVC application I have a shared _Layout.cshtml file that displays the menu for a User
On that View I want to display information from the UserProfile entity - created using SimpleMembership and thus linked to the IPrincipal User that can be accessed directly in the _Layout page.
So I wrote an extension method that makes a call on my UnitOfWork and looks like this:
public static UserProfile GetUserProfile(this IPrincipal u)
{
IUnitOfWork uow = new UnitOfWork();
return uow.UserRepository.GetUserProfile(u);
}
Now this works, but it doesn't smell good because I am instantiating the UnitOfWork rather than injecting it....
I have a BaseController class that looks like this:
public class BaseController : Controller
{
// NOT NECESSARY TO DISPOSE THE UOW IN OUR CONTROLLERS
// Recall that we let IoC inject the Uow into our controllers
// We can depend upon on IoC to dispose the UoW for us
protected MvcApplication.Data.Contracts.IUnitOfWork _Uow { get; set; }
}
(I based some of my code on this answer: https://stackoverflow.com/a/12820444/150342)
I used Package Manager to install StructureMap and this code runs on application start:
public static class StructuremapMvc
{
public static void Start()
{
IContainer container = IoC.Initialize();
DependencyResolver.SetResolver(new StructureMapDependencyResolver(container));
GlobalConfiguration.Configuration.DependencyResolver = new StructureMapDependencyResolver(container);
}
}
As I understand it this injects my concrete UnitOfWork class into my controllers, and handles disposing of the UnitOfWork.
Unfortunately that is as far as my understanding of the IoC goes, and I'm not sure what to do if I want to access the UnitOfWork from somewhere other than the Controller - or whether I can pass the information to the _Layout from my controller. I want to get data onto the _Layout page and I am confused about how to access the UnitOfWork from there, or how to inject the UnitOfWork into an extension method