Unity framework - creating & disposing Entity Framework datacontexts at the appropriate time
- by TobyEvans
Hi there,
With some kindly help from StackOverflow, I've got Unity Framework to create my chained dependencies, including an Entity Framework datacontext object:
using (IUnityContainer container = new UnityContainer())
{
container.RegisterType<IMeterView, Meter>();
container.RegisterType<IUnitOfWork, CommunergySQLiteEntities>(new ContainerControlledLifetimeManager());
container.RegisterType<IRepositoryFactory, SQLiteRepositoryFactory>();
container.RegisterType<IRepositoryFactory, WCFRepositoryFactory>("Uploader");
container.Configure<InjectedMembers>()
.ConfigureInjectionFor<CommunergySQLiteEntities>(
new InjectionConstructor(connectionString));
MeterPresenter meterPresenter = container.Resolve<MeterPresenter>();
this works really well in creating my Presenter object and displaying the related view, I'm really pleased.
However, the problem I'm running into now is over the timing of the creation and disposal of the Entity Framework object (and I suspect this will go for any IDisposable object). Using Unity like this, the SQL EF object "CommunergySQLiteEntities" is created straight away, as I've added it to the constructor of the MeterPresenter
public MeterPresenter(IMeterView view, IUnitOfWork unitOfWork, IRepositoryFactory cacheRepository)
{
this.mView = view;
this.unitOfWork = unitOfWork;
this.cacheRepository = cacheRepository;
this.Initialize();
}
I felt a bit uneasy about this at the time, as I don't want to be holding open a database connection, but I couldn't see any other way using the Unity dependency injection. Sure enough, when I actually try to use the datacontext, I get this error:
((System.Data.Objects.ObjectContext)(unitOfWork)).Connection
'((System.Data.Objects.ObjectContext)(unitOfWork)).Connection'
threw an exception of type 'System.ObjectDisposedException'
System.Data.Common.DbConnection {System.ObjectDisposedException}
My understanding of the principle of IoC is that you set up all your dependencies at the top, resolve your object and away you go. However, in this case, some of the child objects, eg the datacontext, don't need to be initialised at the time the parent Presenter object is created (as you would by passing them in the constructor), but the Presenter does need to know about what type to use for IUnitOfWork when it wants to talk to the database.
Ideally, I want something like this inside my resolved Presenter:
using(IUnitOfWork unitOfWork = new NewInstanceInjectedUnitOfWorkType())
{
//do unitOfWork stuff
}
so the Presenter knows what IUnitOfWork implementation to use to create and dispose of straight away, preferably from the original RegisterType call. Do I have to put another Unity container inside my Presenter, at the risk of creating a new dependency?
This is probably really obvious to a IoC guru, but I'd really appreciate a pointer in the right direction
thanks
Toby