Ninject, multiple service bindings
-
10-07-2019 - |
Question
I am using Ninject to load several modules. When two modules try to bind two different implementations for an interface, ninject raises an error that multiple binding for a service are not allowed.
All other IoC frameworks I'm using (Unity, Windsor, Spring.net, etc) all have the ability to 'register' multiple implementations for an interface.
Let me give a real life example:
public class HealtMonitorEmailAlertServiceModule : StandardModule
{
public override void Load()
{
this.Bind<IAlertService>().To<EmailAlertService>();
}
}
public class HealtMonitorSmsAlertServiceModule : StandardModule
{
public override void Load()
{
this.Bind<IAlertService>().To<SmsAlertService>();
}
}
public class Program
{
static void Main()
{
var emailService = new HealtMonitorEmailAlertServiceModule();
var smsService = new HealtMonitorSmsAlertServiceModule();
IKernel kernel = new StandardKernel(emailService, smsService);
kernel.Get<IAlertService>()
}
}
The above generates an exception, i would expect it to resolve the type registered in the last module to load into the kernel. I have tried the exact same approach using Autofac and it works as I expected.
Solution
Ninject 2.0 has this capability, but Ninject 1.x does not. While 2.0 is still in beta, I'd encourage you to take a look, because 1.x will be end-of-life within a couple of months.