This project is read-only.

Register implementation as singleton

Jun 13, 2013 at 12:34 PM
Is it possible to register an implementation as singleton?
What I mean by this is the following:

Consider a class that implements multiple role interfaces. The implementation only makes sense if there is only one instance of that class.
However, registering the class as singleton for multiple services will result in one singleton instance of that class per service.

To reproduce:
var container = new Container();
container.RegisterSingle<IService, Service>();
container.RegisterSingle<IService2, Service>();

// Will fail:
Assert.Same(container.GetInstance<IService>(), container.GetInstance<IService2>());
Jun 13, 2013 at 2:14 PM
Jun 13, 2013 at 4:25 PM
Edited Jun 13, 2013 at 4:26 PM
As I find the syntax in the link above a bit verbose, I created a small extension method for this scenario:
public static void RegisterSingleImplementation<TImplementation>(
    this Container container, params Type[] serviceTypesToRegisterFor)
    var implementationType = typeof(TImplementation);
    var registration = Lifestyle.Singleton.CreateRegistration(implementationType,
    foreach (var serviceType in serviceTypesToRegisterFor)
        container.AddRegistration(serviceType, registration);
container.RegisterSingleImplementation<Service>(typeof(IService), typeof(IService2));
Jun 13, 2013 at 4:47 PM
Edited Jun 13, 2013 at 4:47 PM
Also take a look at the these extension methods. They allow you to do this:
container.Register<IService, IService2, Service>(Lifestyle.Singleton);
Marked as answer by dot_NET_Junkie on 2/26/2014 at 1:34 PM
Jun 13, 2013 at 4:49 PM
Thanks. Is there a NuGet package for those Code samples?
Jun 13, 2013 at 4:59 PM
Nope. They're just code samples :-).