Search code examples
c#simple-injector

SimpleInjector multiple instances being generated


I´m facing a strange behaviour when using simpleInjector.

The following code illustrates my scenario:

class A: IA, IB<D>{}

Then, i´m registering it, once per interface´s instance, as follows:

foreach (var service in typeof(A).GetInterfaces())
{
    container.RegisterSingle(service, typeof(A));
}

My goal, is to be able to retrieve the same instance (singleton), of A, using either IA or IB. IB stands for a eventlistener interface.

Putting a breakpoint on A´s constructor I can see it being called twice when the container.verify() method is called, meaning that I´m not having a singleton here.

What´s wrong with this scenario? Do I need to threat generics interface in a different fashion?


Solution

  • Register multiple interfaces with the same implementation

    To adhere to the Interface Segregation Principle, it is important to keep interfaces narrow. Although in most situations implementations implement a single interface, it can sometimes be beneficial to have multiple interfaces on a single implementation. Here is an example of how to register this:

    // Impl implements IInterface1, IInterface2 and IInterface3.
    var registration =
        Lifestyle.Singleton.CreateRegistration<Impl>(container);
    
    container.AddRegistration(typeof(IInterface1), registration);
    container.AddRegistration(typeof(IInterface2), registration);
    container.AddRegistration(typeof(IInterface3), registration);
    
    var a = container.GetInstance<IInterface1>();
    var b = container.GetInstance<IInterface2>();
    
    // Since Impl is a singleton, both requests return the same instance.
    Assert.AreEqual(a, b);
    

    Reference: Register multiple interfaces with the same implementation