Search code examples
c#.netsimple-injector

Using the Simple Injector, is it possible to get a singleton by its implementation type?


If I register in the container something like:

container.Register<IShell, ShellViewModel>(Lifestyle.Singleton);

Is there a way to get the same instance using the "implementation type" ShellViewModel?

Example:

container.GetInstance<ShellViewModel>();

The above line returns an instance different from container.GetInstance<IShell>(). How can I make sure the instance is the same for both calls?

I solve it using ResolveUnregisteredType event.

private void ContainerResolveUnregisteredType(
    object sender, UnregisteredTypeEventArgs e)
{
    var producer = container.GetRootRegistrations()
        .FirstOrDefault(r => r.Registration
            .ImplementationType == e.UnregisteredServiceType);
    if (producer != null && producer.Lifestyle == Lifestyle.Singleton)
    {
        var registration = producer.Lifestyle
            .CreateRegistration(
                e.UnregisteredServiceType,
                producer.GetInstance,
                container);
        e.Register(registration);
    }
}

Is it the correct way?


Solution

  • You simply register them both as singleton:

    container.RegisterSingleton<ShellViewModel>();
    container.RegisterSingleton<IShell, ShellViewModel>();
    

    UDPATE

    Confirmed working with a simple unit test:

    [TestMethod]
    public void RegisterSingleton_TwoRegistrationsForTheSameImplementation_ReturnsTheSameInstance()
    {
        var container = new Container();
    
        container.RegisterSingleton<ShellViewModel>();
        container.RegisterSingleton<IShell, ShellViewModel>();
    
        var shell1 = container.GetInstance<IShell>();
        var shell2 = container.GetInstance<Shell>();
    
        Assert.AreSame(shell1, shell2);
    }