假设我有 IRepository 接口及其实现 SqlRepository,它将 LINQ to 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>) { ... }
}
创建 Service 类时是否有任何方法可以使用相同的 DataContext 注入所有三个存储库?
您需要做的就是确保在注册时Datacontext
与您的 Unity 容器一起使用PerResolveLifetimeManager
在配置中:
<type type="<namespace>.DataContext, <assembly>">
<lifetime type="Microsoft.Practices.Unity.PerResolveLifetimeManager, Microsoft.Practices.Unity" />
</type>
或者在代码中:
container.RegisterType<DataContext>(new PerResolveLifetimeManager());
然后每当容器解析Service
任何还需要的依赖项DataContext
将提供完全相同的一个。但接下来的请求要解决Service
将创建一个新的DataContext
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)