Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity framework - reusing instance

nobody loved my first question about this: Creating Entity Framework objects with Unity for Unit of Work/Repository pattern

so I've managed to rephrase it to something you can read without falling asleep/losing the will to live.

I'm creating an object, DataAccessLayer, that takes 2 interfaces in the constructor: IUnitOfWork, and IRealtimeRepository:

public DataAccessLayer(IUnitOfWork unitOfWork,
                       IRealtimeRepository realTimeRepository)
{
    this.unitOfWork = unitOfWork;
    this.realTimeRepository = realTimeRepository;
}

Now, the constructor for the implementation of IRealtimeRepository also takes an IUnitOfWork parameter:

public DemoRepository(IUnitOfWork unitOfWork)
{
    this.unitOfWork = unitOfWork;
}

In the Unity container setup, I then add the two implementations:

container.RegisterType<IUnitOfWork, communergyEntities>();
container.RegisterType<IRealtimeRepository, DemoRepository>();

what happens is that Unity creates 2 new instances of IUnitOfWork (actually an Entity Framework data context), one for the DataAccessLayer constructor, one for the DemoRepository constructor

As this is for the Unit of Work pattern, it's pretty important that the same instance is reused. Any ideas? I see similar questions have been asked before, but not accepted

like image 205
TobyEvans Avatar asked Mar 09 '10 21:03

TobyEvans


1 Answers

You can tell Unity to use a ContainerControlledLifetimeManager:

container.RegisterType<IUnitOfWork, communergyEntities>(new ContainerControlledLifetimeManager());

Alternately you can use RegisterInstance instead of RegisterType, though you have to create it at the time of registration:

container.RegisterInstance<IUnitOfWork>(new CommunergyEntities());
like image 52
Jeff Sternal Avatar answered Sep 28 '22 05:09

Jeff Sternal