为多个接口注册相同的实现

时间:2014-09-08 07:39:41

标签: c# servicestack inversion-of-control

我有一个实现了许多接口的类

public class AwesomeThingClass: IAwesome<Thing>, IAwesomeThing {
    // parameterized constructor, so can't use RegisterAutowiredAs
    public AwesomeThingClass(IClient client, string connectionString) {} 
}

它使用信号量封装了有限基数的多线程操作(我的意思是,只允许同时运行N个这样的操作)。

但是,如果我使用类似

的内容向IoC注册它
container.Register<IAwesome<Thing>>(cont => new AwesomeThingClass(cont.Resolve<IClient>(), connStr))
container.Register<IAwesomeThing>(cont => new AwesomeThingClass(cont.Resolve<IClient>(), connStr))

我最终得到了两个可以使用IAwesome<Thing>IAwesomeThing解决的实例,它允许运行2 * N个操作。我肯定需要为两个接口解析相同的实例。有没有办法实现这一点,除了手动实例化类和registering instance

此问题与Register the same type to multiple interfaces基本相似,但并不重复,因为我在撰写本文时使用的是ServiceStack IoC容器(Func ),而这个问题是关于Unity

2 个答案:

答案 0 :(得分:4)

可能有一个专门用于ServiceStack IoC的简单解决方案,但您也可以使用Lazy<T>从两个lambda中返回相同的值。

var lazy = new Lazy<AwesomeThingClass>(() =>
    new AwesomeThingClass(container.Resolve<IClient>(), connStr));

container.Register<IAwesome<Thing>>(cont => lazy.Value);
container.Register<IAwesomeThing>(cont => lazy.Value);

(我假设lambda的cont参数与container变量的对象相同。)

答案 1 :(得分:0)

你应该能够施展它:

container.Register<IAwesomeThing>(c => 
    new AwesomeThingClass(c.Resolve<IClient>(), connStr));

container.Register(c => (IAwesome<Thing>) c.Resolve<IAwesomeThing>()));