使用构造函数参数的类可以使用Windsor构造函数注入吗?

时间:2014-01-22 20:12:04

标签: c# dependency-injection castle-windsor constructor-injection

public interface ISomething
{
    string SomeMethod(string arg);
}


public class Something : ISomething
{
    public Something(Type type)
    {
        // initialization using type argument
    }

    public Something(string name)
    {
        // initialization using name argument
    }

    public string SomeMethod(string arg)
    {   
        // do something
    }
}       


public class SomethingElse : ISomethingElse
{
    public SomethingElse(ISomething something)
    {
        // ....
    }
}         


public class WindsorInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(Component.For<ISomething>().ImplementedBy<Something>().Named("Something").LifestyleSingleton());
    }
}

(为简洁起见,我省略了标准的Windsor初始化代码。)

但是当创建ISomethingElse的实例时(可能是因为ISomethingElse被注入其他类),Windsor无法解析ISomething构造函数参数,因为它没有知道为类型参数提供什么。

Castle.MicroKernel.Handlers.HandlerException was unhandled by user code
  HelpLink=groups.google.com/group/castle-project-users
  HResult=-2146233088
  Message=Can't create component 'Something' as it has dependencies to be satisfied.

'Something' is waiting for the following dependencies:
- Service 'System.Type' which was not registered.
- Parameter 'name' which was not provided. Did you forget to set the dependency?

1 个答案:

答案 0 :(得分:2)

看看here,这显示了如何添加非服务的依赖项(因此无法通过容器解析)