With any StackOverflow help, I have a Unity Framework for creating bound 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 very well when creating a Presenter object and displaying the corresponding view, I am very pleased.
However, the problem I'm currently facing is related to the timing of creating and deleting an Entity Framework object (and I suspect that this will work for any IDisposable object). Using Unity, this CommunergySQLiteEntities SQL EF object is instantiated as I added its interface, IUnitOfWork, to the MeterPresenter constructor
public MeterPresenter(IMeterView view, IUnitOfWork unitOfWork, IRepositoryFactory cacheRepository) { this.mView = view; this.unitOfWork = unitOfWork; this.cacheRepository = cacheRepository; this.Initialize(); }
I was a little embarrassed at the time, since I did not want to open a database connection, but I could not see another way to use Unity dependency injection. Of course, when I really 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 IoC principle is that you configure all your dependencies at the top, resolve your object, and leave. However, in this case, some child objects, such as a datacontext, should not be initialized at the time the parent Presenter object is created (as you would by passing them in the constructor), but Presenter really needs to know what type to use for IUnitOfWork when it wants to talk to database.
Ideally, I want something like this inside my authorized Lead:
using(IUnitOfWork unitOfWork = new NewInstanceInjectedUnitOfWorkType()) {
So, the facilitator knows which IUnitOfWork implementation to use to create and delete immediately, preferably from the original RegisterType call. Should I put another Unity container inside my presenter, risking creating a new dependency?
This is probably really obvious to the IoC guru, but I really appreciate the pointer in the right direction.