Caliburn.Micro #007 : Bootstrapper with Unity

Unity is one of the most commonly used IOC containers used by developers, and it would be unfair if I don’t include it as a part of the Caliburn.Micro WPF Tutorials (Creating Bootstrappers).  This particular post is dedicated to building bootstrapper for Caliburn.Micro application using Unity as the IoC Container.


The key for creating Bootstrappers for Caliburn.Micro application lies in overriding 4 methods from the BootstrapperBase class. The 4 methods are
  1. Configure
  2. BuildUp
  3. GetInstance
  4. GetAllInstance
The implementation using SimpleContainer and MEF is described in the earlier parts of the Caliburn.Micro Tutorials. Let’s go ahead and implement the Configure method using Unity.
private IUnityContainer _unityContainer;
protected override void Configure()
{
    _unityContainer = new UnityContainer();
    _unityContainer.RegisterInstance<IWindowManager>(new WindowManager());
    _unityContainer.RegisterInstance<IEventAggregator>(new EventAggregator(), new ContainerControlledLifetimeManager());
    //  View Models
    _unityContainer.RegisterInstance<IShellViewModel>(new ShellViewModel());
}
Container using Unity is initialized using the UnityContainer class. RegisterInstance methods are used to register your Classes. For cases, where you need Singletons, you can make use of the ContainerControlledLifeTimeManager as seen in the above example. This place will also hold your ViewModel registrations as well.


Rest of the 3 methods are pretty simple and straightforward to understand.
protected override void BuildUp(object instance)
{
  _unityContainer.BuildUp(instance);
  base.BuildUp(instance);
}
protected override object GetInstance(Type service, string key)
{
  return string.IsNullOrEmpty(key) ? _unityContainer.Resolve(service, key) : _unityContainer.Resolve(service);
}
protected override IEnumerable<object> GetAllInstances(Type service)
{
  return _unityContainer.ResolveAll(service);
}
Finally, similar to earlier Bootstrappers, we use the OnStartup Method to invoke the ShellViewModel.

protected override void OnStartup(object sender, StartupEventArgs e)
{
   DisplayRootViewFor<IShellViewModel>();
}

The complete code sample can be accessed at my Github. The bootstrapper template is also included as a part of Caliburn.Micro Template Pack for WPF.

Advertisement

One thought on “Caliburn.Micro #007 : Bootstrapper with Unity

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s