I actually found it very difficult to plagiarise this work off some documentation so I thought I'd help the cause by spilling how I managed it. I'm not going to talk about how to set up the Repository pattern, Unit of Work pattern, or Unity in general. Just how to make a delicious combination of all three.
In my inventory of classes to wire up I have:
- ContentEntities - this is my ObjectContext
- UnitOfWork - this is my implementation of IUnitOfWork (Google that for guidance)
- EntityRepostory<T> - this is my implementation of IRepository<T> where T:class (again for guidance on this pattern Google it)
- ContentService - This has a dependency property for the ContentRepository of type IRepository<Content>
To wire these all up for the RepositoryPattern to be correctly implemented so that the UnitOfWork is reused correctly I used the following code in my Application_Start() method:
//new container var container = new UnityContainer(); //set up the unit of works to use the singleton pattern (AKA ContainerControlledLifetimeManager) container.RegisterType<IUnitOfWork, UnitOfWork>("contentUow", new ContainerControlledLifetimeManager(), new InjectionConstructor(new SocialEntities())); //get the instance (i have named it to disambiguate in the event of having multiple UOWs (quite likely)) var contentUow = container.Resolve<IUnitOfWork>("contentUow"); //now we have the reference start up a new container container = new UnityContainer() //content repository (any other repositories within the model can use this same contentUow instance) .RegisterType<IRepository<Content>, EntityRepository<Content>>(new InjectionConstructor(contentUow)) .RegisterInstance(typeof(ContentService));
Note I used the ContainerControlledLifetimeManager for the UnitOfWork. There are more for you to choose from, I decided from the description that this is the best for me. Check here for a full list of LifetimeManagers.
This is interesting reading if you are interested in what happens when you ignore the UnitOfWork part of the Repository pattern. Bad things!