我是 IOC 容器的新手,我正在开始使用 NInject。
如果您希望您的构造函数具有非服务且不需要由 IOC 容器实例化的参数,您该怎么办?
例如:
public class Person
{
private readonly string _name;
private readonly IPersonRepository _repository;
public Person(string name, IPersonRepository repository)
{
_name = name;
_repository = repository;
}
......
}
想象一下name是 Person 类的要求,因此,为了确保 Person 始终具有名称,我们要求将其传递给构造函数。
我们如何使用 NInject 获取 Person 的实例?该名称需要由创建新 Person 的应用程序的任何部分传入,而 IOC 容器需要传入 IPersonRepository。
我知道可以使用属性来注入名称或存储库,但这不是一个干净的解决方案 - 我们正在失去一些编程语言的语义能力。
距离我问这个问题已经一年多了,我现在知道的比当时多了。凯文的答案是正确的和最佳实践,但有时您需要使用遗留类并想做一些像我在问题中所做的事情。以下是我使用 NInject 的方法:
public class Person
{
[Inject]
public IPersonRepository PersonRepository { get; set; }
private string _name;
public Person(string name)
{
_name = name;
StaticKernelContainer.Inject(this);
}
}
StaticKernelContainer 的实现可以在 NInject Web 扩展项目中找到。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)