在Castle Windsor中,安装程序代码使用服务方法将依赖项注入另一个服务会是什么样子?

时间:2013-09-08 15:40:27

标签: c# castle-windsor

public class ServiceThatProvidesDep
{
    public Dep GetDep()
    {
        // return dep object
    }
}

public class ServiceThatConsumesDep
{
    public ServiceThatConsumesDep(Dep dep)
    {
        // ...
    }
}

以下是我认为安装程序的外观:

container.Register(Component.For<ServiceThatProvidesDep>());
container.Register(Component.For<Dep>().UsingService<ServiceThatProvidesDep>(s => s.GetDep()));

2 个答案:

答案 0 :(得分:2)

你可以像这样执行UsingFactoryMethod重载:

container.Register(Component.For<ServiceThatProvidesDep>());
container.Register(Component.For<ServiceThatConsumesDep>().LifestyleTransient());
container.Register(Component.For<Dep>().UsingFactoryMethod(kernel => kernel.Resolve<ServiceThatProvidesDep>().GetDep()).LifestyleTransient());

我在使用工厂方法时可能需要它的组件中添加了瞬态生命周期。

答案 1 :(得分:0)

ServiceThatProvidesDep应该是Dep工厂

public interface IDepFactory
{
    public Dep CreateDep();
}

它应该注入使用它的服务<​​/ p>

public class ServiceThatUsesDep
{
    public ServiceThatUesDep( IDepFactory factory )
    ...

这样你就不会试图重新发明东西。