【问题标题】:Can't call component method from Castle Windsor OnCreate无法从 Castle Windsor OnCreate 调用组件方法
【发布时间】: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 对我来说似乎有点局限,因为在第三种情况下,当有多个服务暴露时,它只允许您绑定到您声明的第一个。我必须交换 IService1IService2 才能调用 op2,但这只是在转移问题。

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

【问题讨论】:

标签: castle-windsor


【解决方案1】:

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

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

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

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

供日后参考,here's the relevant documentation.

【讨论】:

  • 我不敢相信我没想过选角。呵呵!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多