问题描述
我一直在尝试使用Ninject实现某些功能(对库没有很好的了解),并且意识到可能无法做我想做的事.
I've been trying to achieve something with Ninject (without a great understanding of the library) and have realized it may not be possible to do what I want.
我有一个我自己引用的项目,并且正在尝试使用Ninject推送一些依赖项,例如:
I've got one of our own projects that I've referenced, and was attempting to use Ninject to push some dependencies in, something like:
public class ImageHelper
{
[Inject]
public static AdaptiveImageSettings Settings { get; set; }
[Inject]
public static IImageSizerFactory Factory { get; set; }
}
}
目标是要进行一些设置(可以由不同的类提供服务)和可以创建ImageHelper类实例的Factory.我不太了解什么是静态的,什么不是当前的.
The aim is to have some settings (which can be served by different classes) and a Factory who can create instances of an ImageHelper class. I'm not too caught up on what's static and what isn't right now.
如果我尝试从引用该项目的WebApplication中使用ImageHelper,则这些属性始终为null.从我的WebApplication中的页面中,具有以下依赖项可以很好地注入:
If I try and use my ImageHelper from a WebApplication referencing that project however these properties are always null. From a Page in my WebApplication with the following the dependencies are injected fine:
public partial class _Default : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
[Inject]
public NetC.Core.ImageSizer.IImageSizerFactory Factory { get; set; }
}
从我读到的内容来看,这是因为内核确实会自动处理,但是我似乎无法找出一种访问内核的方法,因此我可以解析这些属性.有人可以给我一些指导,以说明这在合理可行的情况下是什么,或者下一步可能是什么?到目前为止,我只看到了ServiceLocator反模式,而且似乎找不到合适的扩展名.
From what I've read this is because the Kernel does get handled automatically, but I can't seem to figure out a way of getting access to the Kernel so I can resolve those properties. Can someone give me some pointers on what if this is reasonably possible, or what the next step might be? So far I've only seen the ServiceLocator anti-pattern and can't seem to find an extension that fits the bill.
推荐答案
您应该转到构造函数注入:
You should move to constructor injection:
public class ImageHelper
{
private readonly AdaptiveImageSettings settings;
private readonly IImageSizerFactory factory;
public ImageHelper(AdaptiveImageSettings settings, IImageSizerFactory factory) {
this.settings = settings;
this.factory = factory;
}
}
当您从Ninject请求ImageHelper
时,ninject会自动将适当的依赖项注入其构造函数.构造函数具有许多优点,例如:
When you request an ImageHelper
from Ninject, ninject will automatically inject the proper dependencies into its constructor. Constructor has many advantages such as:
- 它明确说明了一种类型需要什么并成为合同.
- 定义类型不必了解依赖项的生活方式(而ImageHelper会强制其依赖项为单例).
- 不能忘记依赖关系(构造函数需要依赖关系).
因此,只要有可能,请尽可能多地进行构造函数注入.
So whenever you can, go for constructor injection as much as possible.
这篇关于依赖注入到参考项目中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!