简体   繁体   中英

How to resolve instance of base interface with Simple Injector

I have an interface that inherits from another one

public interface ISpecificHandler : IHandler

With Simple Injector I register my type and implementation

container.RegisterSingleton<ISpecificHandler, SpecificHandlerImpl>();

But how can I just resolve IHandler instead of ISpecificHandler ?

//Expect SpecificHandlerImpl as handler
IHandler handler = ServiceLocator.GetInstance<IHandler>(); //error

This throws a InvalidOperationException that the IHandler type is not registered

There are several solutions, but it really depends on what your application really needs. Here are some suggestions.

You just register the implementation twice:

container.Register<IHandler, SpecificHandlerImpl>(Lifestyle.Scoped);
container.Register<ISpecificHandler, SpecificHandlerImpl>(Lifestyle.Scoped);

But perhaps you want to resolve multiple handlers, in which case you will have to probably register them as a collection:

var reg1 = Lifestyle.Singleton.CreateRegistration<SpecificHandlerImpl>();
var reg2 = Lifestyle.Singleton.CreateRegistration<AnotherHandlerImpl>();

container.RegisterCollection<IHandler>(new[] { reg1, reg2 });

You might run into troubles however when using a non-generic IHandler interface, because you will usually have one specific implementation that should be executed in a certain scenario (in other words, you might be violating the Liskov Substitution Principle ). So you'd often be better of using a generic IHandler<T> abstraction where T is a parameter object that contains the values of the handler. In that case there is always a one-to-one mapping between a closed IHandler<T> and an implementation. This article gives a good explanation of the advantages of such design.

But without knowing the problem you're trying to solve, it's hard to say what would be the right solution for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM