0
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()));
4

2 回答 2

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());

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

于 2013-09-08T21:32:40.067 回答
0

ServiceThatProvidesDep 应该是一个 Dep 工厂

public interface IDepFactory
{
    public Dep CreateDep();
}

它应该被注入到使用它的服务中

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

这样,您就不会试图重新发明事物。

于 2013-09-08T18:28:53.343 回答