简体   繁体   中英

Dependency injection into referenced project

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.

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; }
    }
}

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.

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; }
 }

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.

Seems like a bad use case for any container.

Just assign them manually at application startup

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;
    }
}

When you request an ImageHelper from Ninject, ninject will automatically inject the proper dependencies into its constructor. Constructor has many advantages such as:

  • It explicitly states what a type requires and becomes the contract.
  • The defining type doesn't have to know anything about the lifestyle of the dependencies (while your ImageHelper forces its dependencies to be singleton).
  • Dependencies can't be forgotten (the constructor requires them).

So whenever you can, go for constructor injection as much as possible.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM