I use MVC 4 with Unity3 for dependency injection.
Say I have two implementations of a service, like this:
public interface ILogger
{
void Log(string log);
}
public class DefaultLogger : ILogger
{
public void Log(string log)
{
System.Diagnostics.Debug.WriteLine(log, "DefaultLogger");
}
}
public class SoundLogger : ILogger
{
public void Log(string log)
{
System.Media.SystemSounds.Beep.Play();
System.Diagnostics.Debug.WriteLine(log, "SoundLogger");
}
}
Is it possible to inject different implementations to different Controllers? I would like to inject the DefaultLogger to Controller1 and the SoundLogger to Controller2. If it is possible, what do I need to do in Bootstrapper.cs to register this correctly?
Thanks for any feedback!
you may try registering the implementations by name;
UnityContainer container = new UnityContainer();
container.RegisterType<ILogger, DefaultLogger>("Default");
container.RegisterType<ILogger, SoundLogger>("Sound");
then you can use them like the following in the constructors:
public Controller1([Dependency("Default")] ILogger logger)
{
...
}
public Controller2([Dependency("Sound")] ILogger logger)
{
...
}
Or you may use Injection Parameters:
Microsoft Unity. How to specify a certain parameter in constructor?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With