使用Castle注入具有非通用实现的开放通用接口

时间:2011-06-01 08:48:58

标签: c# .net generics dependency-injection castle-windsor

我有一个开放的通用接口,我使用非泛型类实现,我想使用城堡windsor注入这个类,但我正在努力.....

假设我有以下界面

public interface IMyInterface<T>
{
    bool DoSomething(T param);
}

然后我有以下类实现此接口,如此

public class MyClass : IMyInterface<string>
{
    public bool DoSomething(string param)
    {
        // Do Something
        return true;
    }
}

我希望能够像这样使用城堡来解析接口,以便injectObject成为MyClass的一个实例。

WindsorContainer container = new WindsorContainer(new XmlInterpreter(newConfigResource("castle")));
IMyInterface<string> injectedObject = container.Resolve<IMyInterface<string>>();

这可能吗,还是我偏离了轨道?如果可能,我如何设置城堡配置部分?我已经尝试使用'1表示法来指示接口是一个开放的泛型类型,但如果实现不是通用的,那么你会得到一个错误,在这种情况下它不是。

任何帮助表示赞赏

1 个答案:

答案 0 :(得分:4)

我们在我的团队中使用流畅的界面,因为我已经查看了配置文件语法已经有一段时间了。基本原则是:您的服务是IMyInterface<string>,实施类型是MyClass。所以我认为会是这样的:

<component service="Namespace.IMyInterface`1[[System.String, mscorlib]], AssemblyName"
        type="Namespace.MyClass, AssemblyName" />

你说你得到一个错误。错误是什么?我想这是因为您已将服务定义为IMyInterface<>而未提供type参数。如果你想这样做,正如你的问题所暗示的那样,实现类型也必须是通用的:

<component service="Namespace.IMyInterface`1, AssemblyName"
        type="Namespace.MyGenericClass`1, AssemblyName" />

请注意,您可以注册这两个组件。如果您这样做,解析IMyInterface<string>将为您提供MyClass的实例,而解析IMyInterface<AnyOtherType>会为您提供MyGenericClass<AnyOtherType>的实例。

相关问题