问题描述
||
我有一个开放的通用接口,我使用一个非通用类来实现,我想使用城堡温莎注入该类,但是很费劲.....
可以说我有以下界面
public interface IMyInterface<T>
{
bool DoSomething(T param);
}
然后我有以下实现该接口的类,如下所示
public class MyClass : IMyInterface<string>
{
public bool DoSomething(string param)
{
// Do Something
return true;
}
}
我希望能够使用像这样的城堡来解析接口,以使被注入的对象成为MyClass的实例。
WindsorContainer container = new WindsorContainer(new XmlInterpreter(newConfigResource(\"castle\")));
IMyInterface<string> injectedobject = container.Resolve<IMyInterface<string>>();
这可能吗,还是我稍微偏离了轨道?如果可能,如何设置城堡配置部分?我尝试使用\'1表示接口是开放的泛型类型,但是如果实现不是通用的,则会出现错误,在这种情况下不是。
任何帮助表示赞赏
解决方法
我们在团队中使用了流畅的界面,因此自从我查看配置文件语法以来已经有一段时间了。基本原则是:您的服务是
IMyInterface<string>
,实现类型是MyClass
。因此,我认为应该是这样的:
<component service=\"Namespace.IMyInterface`1[[System.String,mscorlib]],AssemblyName\"
type=\"Namespace.MyClass,AssemblyName\" />
你说你得到一个错误。有什么错误?我猜是因为您没有提供type参数就将服务定义为IMyInterface<>
。如果您要这样做,正如您的问题所暗示的那样,实现类型还必须是通用的:
<component service=\"Namespace.IMyInterface`1,AssemblyName\"
type=\"Namespace.MyGenericClass`1,AssemblyName\" />
请注意,您可以注册两个组件。如果这样做,解析re3ѭ将获得MyClass
的实例,而解析IMyInterface<AnyOtherType>
将获得MyGenericClass<AnyOtherType>
的实例。