[英]Repository, IRepository and structuremap
I have an interface IRepository and an implementation EFRepository. 我有一个接口IRepository和一个实现EFRepository。
I use structuremap injection in order to get the repository implementation. 我使用structuremap注入来获取存储库实现。
Right now the EFRepository has constructor with no parameter so structuremap knows to retrieve instances on EFRepository easily. 现在,EFRepository具有没有参数的构造函数,因此structuremap知道可以轻松检索EFRepository上的实例。
Now I need to change the repository implementation so that it will recieve in the constructor parameter that holds the unit of work. 现在,我需要更改存储库实现,以便它将接收保存工作单元的构造函数参数。
My question in such case, how I use structuremap in order to return an instance that initialized with the unit of work? 在这种情况下的问题是,如何使用structuremap来返回以工作单元初始化的实例?
EXAMPLE 例
Until today I used: 直到今天,我仍然使用:
using(IUnitOfWork uow=UnitOfWork.current) {
IRepository rep = ObjectFactory.GetInstance<IRepository<T>>();
//repository operations that uses UnitOfWork.current that initialized above
}// here dispose of UnitOfWork.current
Now I want to use: 现在我要使用:
using(IUnitOfWork uow=new UnitOfWork()) {
//Not sure is this is how I tell sructure map to use contractor that
//get IUnitOfWork)
IRepository rep = ObjectFactory.GetInstance<IRepository<T>>(uow);
//repository operations that uses uow that initialized above
}// here dispose of UnitOfWork
I'm assuming here that your unit of work is request-specific... So you have a service (WCF?) and each incoming request gets its own unit of work. 我在这里假设您的工作单元是特定于请求的...因此,您有一个服务(WCF?),每个传入的请求都具有自己的工作单元。
Then you can configure StructureMap to define a separate unit of work per HTTP Request. 然后,您可以配置StructureMap来为每个HTTP请求定义一个单独的工作单元。 If you need unit testing without HTTP Requests, you can choose for a hybrid lifecycle: per HTTP Request OR per thread.
如果您需要没有HTTP请求的单元测试,则可以选择混合生命周期:每个HTTP请求或每个线程。 StructureMap will figure out what to do at runtime.
StructureMap将弄清楚在运行时该做什么。
ObjectFactory.Configure(x => x.For<IUnitOfWork>()
.HybridHttpOrThreadLocalScoped()
.Use<MyUnitOfWork>());
Your class that needs the constructor injection simply states that it needs an IUnitOfWork: 您需要构造函数注入的类仅声明它需要IUnitOfWork:
public MyClass(IUnitOfWork unit) { ... }
This of course requires that MyClass is also managed/instantiated using StructureMap. 当然,这要求MyClass也必须使用StructureMap进行管理/实例化。
In order to pass a specific instance to ObjectFactory you can use "with": 为了将特定实例传递给ObjectFactory,可以使用“ with”:
IRepository rep = ObjectFactory.With<UnitOfWork>(uow).
GetInstance<IRepository<T>>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.