【发布时间】:2015-09-11 07:52:01
【问题描述】:
我正在使用 Castle Windsor,它通常会摇摆不定,但是我希望它在创建组件时调用我的组件上的方法,并且似乎遇到了 OnCreate 的限制。例如:
interface IService1
{
void op1();
}
interface IService2
{
void op2();
}
class MyComponent : IService1, IService2
{
public void Init() // not part of either service
{
}
public void op1()
{
}
public void op2()
{
}
}
// I want to call the component's Init() method when it's created, which isn't part of the service contract
container.Register(Component.For<IService1, IService2>().ImplementedBy<MyComponent>().OnCreate(s => s.Init()));
// I could call something from IService1
container.Register(Component.For<IService1, IService2>().ImplementedBy<MyComponent>().OnCreate(s => s.op1()));
// But I can't call anything from any of the other services
container.Register(Component.For<IService1, IService2>().ImplementedBy<MyComponent>().OnCreate(s => s.op2()));
第一次注册不会编译,抱怨它“无法解析符号 Init”,因为传递给委托的实例是 IService1 类型。 OnCreate 对我来说似乎有点局限,因为在第三种情况下,当有多个服务暴露时,它只允许您绑定到您声明的第一个。我必须交换 IService1 和 IService2 才能调用 op2,但这只是在转移问题。
为什么委托中传递的类型不是被注册组件的类型?然后我可以随意调用我喜欢的任何方法。有没有解决的办法?假设我不能将Init() 代码放在组件的构造函数中。
【问题讨论】:
-
我正要提到Startable facility,但它确实只适用于单身人士。
标签: castle-windsor