结合DI与构造函数参数? [英] Combining DI with constructor parameters?
问题描述
如何将构造函数注入与手动"构造函数参数结合起来?即.
How do I combine constructor injection with "manual" constructor parameters? ie.
public class SomeObject
{
public SomeObject(IService service, float someValue)
{
}
}
我的DI容器应在哪里解析/注入IService,并应指定someValue.如何将两者混在一起?
Where IService should be resolved/injected by my DI container, and someValue should be specified. How do I mix the two?
推荐答案
应尽可能避免这种构造.因此,请问问自己:该参数是否真的需要作为构造函数参数?还是可以通过将参数传递给您在对象上执行的方法来将SomeObject替换为无状态的对象,从而使依赖该对象的每个人都可以重用它?
Such constructs should be avoided whenever possible. Therefore, ask yourself: is this parameter really required as constructor argument? Or can SomeObject be replaced by a stateless one which is reused by everyone that depends on it by passing the parameter to the method you execute on the object?
例如代替
public class SomeObject
{
private float someValue
public SomeObject(IService service, float someValue)
{
this.someValue = someValue
}
public float Do(float x)
{
return this.Service.Get(this.someValue) * x;
}
}
使用
public class SomeObject
{
public SomeObject(IService service)
{
}
public float Do(float x, float someValue)
{
return this.Service.Get(someValue) * x;
}
}
如果需要,请去工厂:
If it is required go for a factory:
public interface ISomeObjectFactory
{
ISomeObject CreateSomeObject(float someValue);
}
public class SomeObjectFactory : ISomeObjectFactory
{
private IKernel kernel;
public SomeObjectFactory(IKernel kernel)
{
this.Kernel = kernel;
}
public ISomeObject Create(float someValue)
{
return this.kernel.Get<ISomeObject>(WithConstructorArgument("someValue", someValue);
}
}
预览: Ninject 2.4不再需要实现,但允许
Preview: Ninject 2.4 won't require the implementation anymore but allow
kernel.Bind<ISomeObjectFactory>().ToFactory(); // or maybe .AsFactory();
这篇关于结合DI与构造函数参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!