统一框架 - 再利用的实例 [英] Unity framework - reusing instance

查看:138
本文介绍了统一框架 - 再利用的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

没有人爱我的第一个问题,关于这一点: <一href="http://stackoverflow.com/questions/2407636/creating-entity-framework-objects-with-unity-for-unit-of-work-repository-pattern">http://stackoverflow.com/questions/2407636/creating-entity-framework-objects-with-unity-for-unit-of-work-repository-pattern

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.

我创建一个对象,DataAccessLayer,这需要2接口,在构造函数中:IUnitOfWork和IRealtimeRepository:

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;
}

现在,该构造IRealtimeRepository的实施也需要一个IUnitOfWork参数:

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

发生的事情是团结创建IUnitOfWork(实际上是一个实体框架数据上下文),一个用于DataAccessLayer构造,一个2新实例为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

由于这是工作模式的单位,这是pretty的重要的是,同一个实例是重复使用。有任何想法吗?我看到类似的问题已经被问过,但没有被接受。

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

推荐答案

您可以告诉统一使用<一个href="http://msdn.microsoft.com/en-us/library/dd203242.aspx">ContainerControlledLifetimeManager:

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

或者您可以使用 RegisterInstance 而不是<一href="http://msdn.microsoft.com/en-us/library/microsoft.practices.unity.unitycontainerbase.registertype.aspx"><$c$c>RegisterType,虽然你有在注册时创建它:

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

container.RegisterInstance<IUnitOfWork>(new CommunergyEntities());

这篇关于统一框架 - 再利用的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆