结合DI与构造函数参数?

编程入门 行业动态 更新时间:2024-10-12 20:28:51
本文介绍了结合DI与构造函数参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何将构造函数注入与手动"构造函数参数结合起来?即.

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与构造函数参数?

本文发布于:2023-10-28 04:47:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1535568.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:函数   参数   DI

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!