By registering a singleton through SimpleInjector and return the same instance, it implements for different interfaces

Imagine that I have the following:

public interface IocInterface1 { } public interface IocInterface2 { } public class IocImpl : IocInterface1, IocInterface2 { } 

I would like that if I try to get any instance of the above classes / interfaces through IoC, I get the same instance, and not one singleton for each type. Example: b1 and b2 below should be true:

 _container.RegisterSingle<IocInterface1, IocImpl>(); _container.RegisterSingle<IocInterface2, IocImpl>(); _container.RegisterSingle<IocImpl, IocImpl>(); var test1 = _container.GetInstance<IocInterface1>(); var test2 = _container.GetInstance<IocInterface2>(); var test3 = _container.GetInstance<IocImpl>(); bool b1 = test1 == test2; bool b2 = test2 == test3; 

Is it possible?

+7
source share
1 answer

If you want to register several types with the same registration, you will need a singleton registration object for your implementation type IocImpl .

Then you need to use AddRegistration to add this registration for different services: IocInterface1 , IocInterface2 , etc.:

 var _container = new Container(); var registration = Lifestyle.Singleton.CreateRegistration<IocImpl, IocImpl>(_container); _container.AddRegistration(typeof(IocImpl), registration); _container.AddRegistration(typeof(IocInterface1), registration); _container.AddRegistration(typeof(IocInterface2), registration); 

as described in the documentation: Register multiple interfaces with the same implementation

Alternatively, you can also do the mapping using delegates:

 _container.RegisterSingle<IocImpl>(); _container.RegisterSingle<IocInterface1>(() => container.GetInstance<IocImpl>()); _container.RegisterSingle<IocInterface2>(() => container.GetInstance<IocImpl>()); 

In most cases, both examples are functionally equivalent, but the former is preferable.

+10
source

All Articles