views:

440

answers:

1

nobody loved my first question about this: http://stackoverflow.com/questions/2407636/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

+3  A: 

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());
Jeff Sternal
c'est magnifique! Merci monsieur!
TobyEvans
My pleasure - you'd think the documentation might mention singleton somewhere, wouldn't you? :)
Jeff Sternal