无法从 Castle Windsor OnCreate 调用组件方法

Can't call component method from Castle Windsor OnCreate

我正在使用 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()));

第一次注册不会编译,抱怨它 "cannot resolve symbol Init" 因为传递给委托的实例是类型 IService1OnCreate 对我来说似乎有点受限,因为在第三种情况下,当有多个服务公开时,它只允许您绑定到您声明的第一个服务。我必须交换 IService1IService2 才能调用 op2,但这只是在转移问题。

为什么在委托中传递的类型不是正在注册的组件的类型?然后我就可以随意调用任何我喜欢的方法了。有没有解决的办法?假设我无法将 Init() 代码放入组件的构造函数中。

不要被 C# 的强类型特性所束缚

是的,API 的构造方式基于组件的第一个服务,但您始终可以将其转换为实际类型(或辅助服务)

.OnCreate(s => ((MyComponent)s).Init())

或者,实施 Castle.Core.IInitializableSystem.ComponentModel.ISupportInitialize(如果您不希望您的组件引用 Windsor),那么您根本不需要 .OnCreate()

供将来参考,here's the relevant documentation.