简体   繁体   中英

Accessing Container instance with LighInject

When using LightInject, how can you use access the Container instance in contexts other than initial registration/bootstrapping? I followed LightInject's getting started guide and google around, but didn't find anything like that.

For reference, I present how this is achieved in two other IoC frameworks.

Ninject

When using Ninject so I'm used to having the IKernel type automatically bound to the Kernel (Container on LighInject), so a class with a constructor like this:

public MyClass(IKernel kernel)
{
    var myInstance = kernel.Get<IMyType>();
}

will be able to use kernel to retrieve instances.

SimpleIoC

When using SimpleIoC, the framework that comes with MvvmLight, you can use a static property (SimpleIoC.Default) to achieve the same purpose:

var myInstance = SimpleIoc.Default.GetInstance<IMyType>();

Short story

No such thing is provided out of the box by LightInject.

Elaboration

Doing this will imply a ServiceLocator kind of thing which most people, LightInject creator included, see as an anty-pattern that must be avoided. The idea is for the ServiceContainer (or Kernel as it's known on ninject) to be used exclusively during startup.

My take on it

In my case, I have a WPF application with MvvmLight. I want to follow the ViewModelLocator approach promoted by this library, which pretty much requires a ServiceLocator kind of thing.

On MvvmLight, ViewModelLocator is supposed to hold instances of each ViewModel and also is supposed to be set up as a resource on the App.xaml file. This implies ViewModelLocator absolutely needs to have a parameterless constructor, which makes using the IoC framework to bind references impossible.

My solution was to create a Singleton to expose the ServiceContainer so it can be referenced from the ViewModelLocator for providing instances fo the ViewModels.

The following discussion was very interesting and provided me with different points of view about this problem:

How to handle dependency injection in a WPF/MVVM application

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