Register implementation as singleton

Jun 13, 2013 at 11:34 AM
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 1:14 PM
Jun 13, 2013 at 3:25 PM
Edited Jun 13, 2013 at 3: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,
                                                              implementationType,
                                                              container);
    foreach (var serviceType in serviceTypesToRegisterFor)
        container.AddRegistration(serviceType, registration);
}
Usage:
container.RegisterSingleImplementation<Service>(typeof(IService), typeof(IService2));
Coordinator
Jun 13, 2013 at 3:47 PM
Edited Jun 13, 2013 at 3: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 3:49 PM
Thanks. Is there a NuGet package for those Code samples?
Coordinator
Jun 13, 2013 at 3:59 PM
Nope. They're just code samples :-).