Search code examples
c#dependency-injectioninversion-of-controlioc-containersimple-injector

Registering a singleton via SimpleInjector and return the same instance, for different interfaces it implements


Imagine I have the below:

public interface IocInterface1 { }

public interface IocInterface2 { }

public class IocImpl : IocInterface1, IocInterface2 { }

I would like that if I try to get any instance of the above classes/interfaces via IoC, I get the exact same instance, not one singleton per type. Example, b1 and b2 below should be true:

_container.RegisterSingle<IocInterface1, IocImpl>();
_container.RegisterSingle<IocInterface2, IocImpl>();
_container.RegisterSingle<IocImpl, IocImpl>();

var test1 = _container.GetInstance<IocInterface1>();
var test2 = _container.GetInstance<IocInterface2>();
var test3 = _container.GetInstance<IocImpl>();

bool b1 = test1 == test2;
bool b2 = test2 == test3;

Is this possible?


Solution

  • If you want to register a multiple types with the same registration then you will need a singleton registration object for your implementation type IocImpl.

    Then you need to use AddRegistration to add this registration for the different services: IocInterface1, IocInterface2 etc.:

    var _container = new Container();
    var registration =
        Lifestyle.Singleton.CreateRegistration<IocImpl, IocImpl>(_container);
    
    _container.AddRegistration(typeof(IocImpl), registration);
    _container.AddRegistration(typeof(IocInterface1), registration);
    _container.AddRegistration(typeof(IocInterface2), registration);
    

    as described in the documenation: Register multiple interfaces with the same implementation

    Alternatively, you can also make a mapping using delegates:

    _container.RegisterSingle<IocImpl>();
    _container.RegisterSingle<IocInterface1>(() => container.GetInstance<IocImpl>());
    _container.RegisterSingle<IocInterface2>(() => container.GetInstance<IocImpl>());
    

    In most cases both examples are functionally equivalent, but the former is preferred.