在几个类型的统一注入相同的DataContext实例 [英] Inject same DataContext instance across several types with Unity

查看:302
本文介绍了在几个类型的统一注入相同的DataContext实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有IRepository接口及其实现SqlRepository这需要作为一个参数的LINQ to SQL的DataContext。假设还有,我有IService接口及其实现服务的需要三个IRepository,IRepository和IRepository。演示代码如下:

Suppose I have IRepository interface and its implementation SqlRepository that takes as an argument LINQ to SQL DataContext. Suppose as well that I have IService interface and its implementation Services that takes three IRepository, IRepository and IRepository. Demo code is below:

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>) { ... }
}

这是任何方式,同时创造服务类具有相同的DataContext注入三个库?

Is it any way while creating Service class to inject all three repositories with the same DataContext?

推荐答案

所有你需要做的就是确保当你用统一的容器使用登记的DataContext PerResolveLifetimeManager 无论是在配置:

All you need to do is make sure when you register the Datacontext with your Unity container use the PerResolveLifetimeManager either in config:

<type type="<namespace>.DataContext, <assembly>">
    <lifetime type="Microsoft.Practices.Unity.PerResolveLifetimeManager, Microsoft.Practices.Unity" />
</type>

或代码:

container.RegisterType<DataContext>(new PerResolveLifetimeManager());



然后依赖这也需要一个的DataContext 将提供完全一样的。但接下来的请求来解析服务将创建一个新的的DataContext

then whenever the container resolves the Service any dependencies which also require a DataContext will be provided with exactly the same one. But the next request to resolve Service will create a new DataContext.

这篇关于在几个类型的统一注入相同的DataContext实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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