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()));
答案 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 )
...
这样你就不会试图重新发明东西。