【问题标题】:Castle Windsor - Resolving a generic implementation to a base typeCastle Windsor - 将通用实现解析为基本类型
【发布时间】:2010-06-14 17:14:02
【问题描述】:

我正在尝试将 Windsor 用作工厂,以提供基于 XAbstractBase 子类型(在我的例子中是抽象消息基类)的规范实现。

我有如下代码:

public abstract class XAbstractBase { }
public class YImplementation : XAbstractBase { }
public class ZImplementation : XAbstractBase { }

public interface ISpecification<T> where T : XAbstractBase
{
    bool PredicateLogic();
}

public class DefaultSpecificationImplementation : ISpecification<XAbstractBase>
{
    public bool PredicateLogic() { return true; }
}

public class SpecificSpecificationImplementation : ISpecification<YImplementation>
{
    public bool PredicateLogic() { /*do real work*/ }
}

我的组件注册码是这样的:

container.Register(
    AllTypes.FromAssembly(Assembly.GetExecutingAssembly())
    .BasedOn(typeof(ISpecification<>))
    .WithService.FirstInterface()
)

当我尝试解析 ISpecification&lt;YImplementation&gt; 时,这很好用;它正确解析SpecificSpecificationImplementation

但是,当我尝试解析ISpecification&lt;ZImplementation&gt;Windsor 时会抛出异常:

"No component for supporting the service ISpecification'1[ZImplementation, AssemblyInfo...] was found"

如果没有注册更多具体实现,Windsor 是否支持将通用实现解析为基类?

【问题讨论】:

    标签: c# generics castle-windsor


    【解决方案1】:

    请参阅this 帖子。

    更新

    好的,我现在明白你做错了什么。 ISpecification&lt;ZImplementation&gt;你没有服务,所以温莎解决不了也就不足为奇了。

    这根本不是温莎问题。

    【讨论】:

    • 这是我在这里发布问题之前发现的更好的帖子之一。我正在寻找的是是否有可能仅使用 Windsor 的构建来解决零个或多个情况(该帖子仅解决一个或多个情况,但我认为添加默认返回值将是微不足道的) - 设施。如果我无论如何都要写一个工厂,我更有可能像往常一样注册它并注入它。
    • 好的;我明白为什么这是不可能的。谢谢!
    • @adriaanp 链接现已修复。
    【解决方案2】:

    您可以将其注册为开放泛型以提供后备,例如

    public class DefaultSpecificationImplementation<T> : ISpecification<T>
        where T : XAbstractBase
    {
        public bool PredicateLogic() { return true; }
    }
    

    作为

    Component.For(typeof(ISpecification<>))
        .ImplementedBy(DefaultSpecificationImplementation<>)
    

    那么当 Windsor 找不到具体的实现时,就会使用泛型的

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-18
      • 2012-06-06
      • 1970-01-01
      • 1970-01-01
      • 2016-02-26
      相关资源
      最近更新 更多