Unity framework - reusing instance

好久不见. 提交于 2019-12-07 04:38:10

问题


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


回答1:


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());


来源:https://stackoverflow.com/questions/2412563/unity-framework-reusing-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!