Ser*_*jus 6 c# datacontext dependency-injection unity-container
假设我有IRepository接口及其实现SqlRepository,它将LINQ作为参数作为SQL DataContext的参数.假设我有IService接口及其实现服务,它需要三个IRepository,IRepository和IRepository.演示代码如下:
public interface IRepository<T> { }
public class SqlRepository<T> : IRepository<T>
{
public SqlRepository(DataContext dc) { ... }
}
public interface IService<T> { }
public class Service<T,T1,T2,T3> : IService<T>
{
public Service(IRepository<T1> r1, IRepository<T2>, IRepository<T3>) { ... }
}
Run Code Online (Sandbox Code Playgroud)
在创建Service类以使用相同的DataContext注入所有三个存储库时,是否有任何方法?
您需要做的就是确保在Datacontext使用Unity容器注册时使用PerResolveLifetimeManagerconfig中的任何一个:
<type type="<namespace>.DataContext, <assembly>">
<lifetime type="Microsoft.Practices.Unity.PerResolveLifetimeManager, Microsoft.Practices.Unity" />
</type>
Run Code Online (Sandbox Code Playgroud)
或在代码中:
container.RegisterType<DataContext>(new PerResolveLifetimeManager());
Run Code Online (Sandbox Code Playgroud)
然后每当容器解析Service任何依赖关系时,也需要DataContext提供完全相同的依赖关系.但下一个要求解决的请求Service将创建一个新的DataContext.
| 归档时间: |
|
| 查看次数: |
4457 次 |
| 最近记录: |