Unity framework - reusing an instance

No one loved my first question about this: Creating Entity Framework objects with Unity for unit of work / repository template

so I managed to rephrase it to something that you can read without falling asleep / losing the desire to live.

I create a DataAccessLayer object that accepts two interfaces in the constructor: IUnitOfWork and IRealtimeRepository:

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

Now the constructor for implementing IRealtimeRepository also accepts the IUnitOfWork parameter:

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

In setting up the Unity container, I then add two implementations:

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

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

As this is done for the Unit of Work template, it is quite important that the same instance is reused. Any ideas? I see that similar questions were asked before but not accepted.

+6
unit-of-work unity-container
source share
1 answer

You can tell Unity to use ContainerControlledLifetimeManager :

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

Alternatively, you can use RegisterInstance instead of RegisterType , although you must create it during registration:

 container.RegisterInstance<IUnitOfWork>(new CommunergyEntities()); 
+6
source share

All Articles