Reputation: 3902
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.
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.
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>();
Upvotes: 0
Views: 568
Reputation: 3902
No such thing is provided out of the box by LightInject.
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.
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
Upvotes: 0