Reputation: 85
I'm trying to understand idea of the IoC Containers. I found some sources that say static class for IoC Container is bad idea, but I can't find good example of not using static in this container. I'm trying to figure it out on my own, but with none results. I'm using Unity IoC Container in my WPF application, but I don't need help with views and viewmodels connection using IoC, because I understood it. I want to inject some registered objects into constructor of my viewmodel:
public class MyViewModel
{
private readonly IExceptionLogger _exceptionLogger;
public MyViewModel(IExceptionLogger exceptionLogger)
{
_exceptionLogger = exceptionLogger;
}
}
My class of container:
public class Bootstrapper
{
private readonly IUnityContainer _container;
public Bootstrapper()
{
_container = new UnityContainer();
}
public void RegisterTypes()
{
_container.RegisterType<IExceptionLogger, ExceptionLogger>();
}
}
Now, I'm stuck. I hoped that if I would add this to my App.xaml.cs, new instance of ExceptionLogger will be sent to constructor:
protected override void OnStartup(StartupEventArgs e)
{
Bootstrapper bootstrapper = new Bootstrapper();
bootstrapper.RegisterTypes();
base.OnStartup(e);
}
But, unfortunately nothing is sent to it. I know that I miss something, but I don't know what.
If somebody knows any good articles about non-static classes for IoC Containers, I will be grateful. If somebody knows what do I miss in my code, please, tell me also.
Upvotes: 0
Views: 228
Reputation: 5549
In a nutshell, unless there's some infrastructure instructing the container to provide types, nothing will happen automatically. Such infrastructure doesn't exist out of the box in WPF as far as I know, so you'll need to do it manually or use an MVVM framework that helps you do that (I've used Caliburn.Micro before and I believe their docs do a fairly good job of explaining things, though I can't say I'm a big fan of everything they do in that framework).
If you want to do things manually to get a feel of how things work, you'll need to use the container to construct your types (that's the easiest way). Just use container.Resolve<IInterface>()
to get the implementation of IInterface - in your case calling container.Resolve<IExceptionLogger>()
will return an ExceptionLogger
. The interesting parts come when you register a class with a constructor having parameters of other registered interfaces - that way you can construct an entire object graph in one go.
In WPF you can register views and viewmodels in a similar way Caliburn does, and then have a bit of infrastructure that binds everything together. Then only those few classes comprising the infrastructure will need access to the container. I'd recommend starting with an MVVM framework that handles a lot of this for you out of the box.
The details are extensively discussed in many questions on stack overflow, such as Where to place and configure IoC container in a WPF application?
Upvotes: 3