我有一个开放的通用接口(interface),我用一个非通用类实现它,我想使用温莎城堡注入(inject)这个类,但我很挣扎......
假设我有以下界面
public interface IMyInterface<T>
{
bool DoSomething(T param);
}
然后我有下面的类,像这样实现这个接口(interface)
public class MyClass : IMyInterface<string>
{
public bool DoSomething(string param)
{
// Do Something
return true;
}
}
我希望能够像这样使用 caSTLe 解析接口(interface),以便注入(inject)的对象成为 MyClass 的实例。
WindsorContainer container = new WindsorContainer(new XmlInterpreter(newConfigResource("castle")));
IMyInterface<string> injectedObject = container.Resolve<IMyInterface<string>>();
这可能吗,还是我稍微偏离了轨道?如果可能的话,我如何设置城堡配置部分?我尝试使用 '1 表示法来指示该接口(interface)是一个开放的泛型类型,但如果实现不是泛型的,则会出现错误,在本例中它不是泛型的。
感谢任何帮助
最佳答案
我们在我的团队中使用流畅的界面,所以我已经有一段时间没有查看配置文件语法了。基本原则是这样的:您的服务是IMyInterface<string>
实现类型为MyClass
。所以我认为它会是这样的:
<component service="Namespace.IMyInterface`1[[System.String, mscorlib]], AssemblyName"
type="Namespace.MyClass, AssemblyName" />
你说你收到一个错误。错误是什么?我猜这是因为您将服务定义为 IMyInterface<>
不提供类型参数。如果您想这样做,正如您的问题所暗示的那样,实现类型也必须是通用的:
<component service="Namespace.IMyInterface`1, AssemblyName"
type="Namespace.MyGenericClass`1, AssemblyName" />
请注意,您可以注册这两个组件。如果您这样做,请解决 IMyInterface<string>
将为您提供 MyClass
的实例,同时解决 IMyInterface<AnyOtherType>
将为您提供 MyGenericClass<AnyOtherType>
的实例.
关于c# - 使用 CaSTLe 注入(inject)具有非通用实现的开放通用接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6198518/