温莎城堡:强制解析器使用指定构造 [英] Castle Windsor: Force resolver to use specified constructor

查看:170
本文介绍了温莎城堡:强制解析器使用指定构造的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是例子:

interface IComponentA {};

class ComponentA : IComponentA { };

interface IComponentB { };

class ComponentB : IComponentB { };

interface IComponentC { };

class ComponentC : IComponentC
{
    public ComponentC(IComponentA a)
    {
        Console.WriteLine("Constructor A"); 
    }

    public ComponentC(IComponentB b) 
    {
        Console.WriteLine("Constructor B");
    }
};



所有这些组件注册在温莎城堡的容器中。

All these components are registered in Castle Windsor container.

但类 ComponentC 有2个重载的构造函数。当 ComponentC 被激活其中任何一个都可以使用。

But class ComponentC has 2 overloaded constructors. Any of them can be used when ComponentC is being activated.

我需要 ComponentC( IComponentB二)要使用构造

有关我使用UsingFactoryMethod()方法来解决了一下:

For a moment I'm using UsingFactoryMethod() method to resolve that:

container
    .Register(Component
        .For<IComponentA>()
        .ImplementedBy<ComponentA>())
    .Register(Component
        .For<IComponentB>()
        .ImplementedBy<ComponentB>())
    .Register(Component
        .For<IComponentC>()
        .UsingFactoryMethod(() => new ComponentC(
            container.Resolve<IComponentB>())));



它的工作原理,但可能温莎城堡提供了一些更好的方法来做到这一点?

It works, but probably Castle Windsor provides some better way to do that?

任何帮助,非常感谢。

感谢。

推荐答案

温莎不会为这种情况提供支持,因为它打破基于被不成文的假设它(和大多数容器)之一:所有的构造都是一样的

Windsor doesn't provide support for this scenario, because it breaks one of the unwritten assumptions it (and most containers) operates based on: "all constructors are created equal".

这意味着什么,是,不管哪个构造的它的动产应该有在组件的行为没有功能上的差别。所有的事情都是平等的更多依赖关系的组件具有更多的功能它都有,这就是为什么温莎往往会先挑贪婪构造,但如果像你我想说两件事正在发生:

What that means, is that regardless of which constructor it choses there should be no functional differences in the behaviour of the component. All things being equal the more dependencies a component has the more capabilities it has, that's why Windsor will tend to pick greedier constructors first, but in case like yours I'd say either of two things are happening:


  • 您的组件实际上可能是伪装为一体的两个组成部分。在这种情况下,你可能会想拆呢。

  • 您的组件实际上并既依赖它进行操作,因此,它应该有一个构造函数他们两个。

我见过另一种情况是类似的东西:

Another scenario I've seen is something like that:

public class Foo
{
   public Foo(ISession session){/*code*/}
   public Foo(ISessionFactory factory):this(factory.OpenSession()){}
}

虽然这似乎是一个聪明的想法,首先,在最好是多余的,混乱和不必要的。如果你的情况是这样的,我只是删除第二个构造函数。

While this might seem like a clever idea at first, at best it's superfluous, confusing and unnecessary. If your case looks like this one, I'd just remove the second constructor.

这篇关于温莎城堡:强制解析器使用指定构造的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆