Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unity3 in MVC - register specifc Implementations

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!

like image 856
Rince2 Avatar asked Jun 24 '26 11:06

Rince2


1 Answers

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?

like image 146
daryal Avatar answered Jun 27 '26 02:06

daryal