开发者

Unity framework - reusing instance

开发者 https://www.devze.com 2022-12-22 15:52 出处:网络
nobody loved my first question about this: Creating Entity Framework objects with Unity for Unit of Work/Repository pattern

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 questio开发者_运维问答ns have been asked before, but not accepted


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号