【问题标题】:Injecting a primitive property in a base class with Castle Windsor使用 Castle Windsor 在基类中注入原始属性
【发布时间】:2011-04-20 11:59:24
【问题描述】:

我有如下接口定义:

public interface ICommandHandler
{
    ILogger Logger { get; set; }
    bool SendAsync { get; set; }
}

我有多个实现ICommandHandler 需要解决。虽然 Castle Windows 会自动注入 Logger 属性,但当注入 ILogger 时,我找不到将 SendAsync 属性配置为在创建新实例期间由 Windsor 设置为 true 的方法。

更新

命令处理程序实现了一个从基本接口继承的通用接口:

public interface ICommandHandler<TCommand> : ICommandHandler
    where TCommand : Command
{
     void Handle(TCommand command);
}

这是我的配置:

var container = new WindsorContainer();

container.Register(Component
     .For<ICommandHandler<CustomerMovedCommand>>()
     .ImplementedBy<CustomerMovedHandler>());
container.Register(Component
     .For<ICommandHandler<ProcessOrderCommand>>()
     .ImplementedBy<ProcessOrderHandler>());
container.Register(Component
     .For<ICommandHandler<CustomerLeftCommand>>()
     .ImplementedBy<CustomerLeftHandler>());

温莎城堡有什么方法可以做到这一点?

【问题讨论】:

    标签: c# .net dependency-injection castle-windsor ioc-container


    【解决方案1】:
    .DependsOn(Proprerty.ForKey("sendAsync").Eq(true))
    

    或匿名类型

    .DependsOn(new{ sendAsync = true })
    

    关于更新的问题,您需要的是以下几行:

    container.Register(AllTypes.FromThisAssembly()
       .BasedOn(typeof(ICommandHandler<>))
       .WithService.Base()
       .Configure(c => c.DependsOn(new{ sendAsync = true })
                        .Lifestyle.Transient));
    

    这样,您可以一次性注册和配置所有处理程序,并且在添加新处理程序时,您无需返回将它们添加到注册代码中。

    我建议reading through the documentation,因为基于约定的注册 API 远不止这些。

    【讨论】:

    • 感谢@Krzysztof。我必须在每个具体的命令注册上应用这个.DependsOn,还是可以应用一次?
    • 这取决于您如何注册它们。它必须进入每个组件,但如果您通过约定注册它们,您只需编写一次代码。
    • 我使用“正常”注册(请参阅我的更新)。你能指出我如何通过约定来做到这一点的例子吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-17
    • 2011-08-09
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多