Multiple interfaces to a single concrete class

Jan 12, 2015 at 2:15 PM
Edited Jan 12, 2015 at 2:22 PM

Is it possible to have multiple interfaces return the same concrete type with a singleton lifestyle?

For example;

public interface IBase { }
public interface ICustom : IBase { }

public class Custom : ICustom { }

I'd like to be able to have either IBase or ICustom in my constructors, for injection, but be returned the same singleton object.


I did just think about doing the below, but it seems a little odd to do it like this.
        container.Register<ICustom, Custom>(Lifestyle.Singleton);
        container.Register<IBase>(() => container.GetInstance<ICustom>());
It would be nicer to do something like;
        container.Register(new [] { typeof(IBase), typeof(ICustom) }, typeof(Custom), Lifestyle.Singleton);
Thanks very much in advance.

Jan 12, 2015 at 2:42 PM
Edited Jan 12, 2015 at 2:42 PM
This came up a little while ago ....

If you need IBase and ICustom to be the exact same instance you need to register a Registration:
var registration = Lifestyle.Singleton.CreateRegistration<Custom>(container);
container.AddRegistration(typeof(IBase), registration);
container.AddRegistration(typeof(ICustom), registration);
Jan 12, 2015 at 2:46 PM
Thanks for the quick reply, is the method you mentioned preferable over the method shown in my edit?
Jan 12, 2015 at 3:12 PM
Edited Jan 12, 2015 at 3:12 PM
Well they both work :-)

.... but I would say you should use CreateRegistration to give the container as much information as possible.
Marked as answer by dot_NET_Junkie on 2/2/2015 at 12:18 PM
Jan 12, 2015 at 3:15 PM
Ok, I'll switch it over then :). Thanks very much for the help.