如何使用 Simple Injector 解析基本接口的实例
How to resolve instance of base interface with Simple Injector
我有一个接口继承自另一个接口
public interface ISpecificHandler : IHandler
使用 Simple Injector 我注册了我的类型和实现
container.RegisterSingleton<ISpecificHandler, SpecificHandlerImpl>();
但是我怎样才能解决 IHandler
而不是 ISpecificHandler
?
//Expect SpecificHandlerImpl as handler
IHandler handler = ServiceLocator.GetInstance<IHandler>(); //error
这会引发 InvalidOperationException
IHandler 类型未注册
有多种解决方案,但这实际上取决于您的应用程序真正需要什么。这里有一些建议。
您只需注册两次实现:
container.Register<IHandler, SpecificHandlerImpl>(Lifestyle.Scoped);
container.Register<ISpecificHandler, SpecificHandlerImpl>(Lifestyle.Scoped);
但也许您想解析多个处理程序,在这种情况下,您可能必须将它们注册为一个集合:
var reg1 = Lifestyle.Singleton.CreateRegistration<SpecificHandlerImpl>();
var reg2 = Lifestyle.Singleton.CreateRegistration<AnotherHandlerImpl>();
container.RegisterCollection<IHandler>(new[] { reg1, reg2 });
你可能 运行 但是当使用非通用 IHandler
接口时,你可能会遇到麻烦,因为你通常会有一个特定的实现应该在特定场景中执行(换句话说,你可能会违反 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 很好地解释了这种设计的优点。
但在不知道您要解决的问题的情况下,很难说什么是适合您的解决方案。
我有一个接口继承自另一个接口
public interface ISpecificHandler : IHandler
使用 Simple Injector 我注册了我的类型和实现
container.RegisterSingleton<ISpecificHandler, SpecificHandlerImpl>();
但是我怎样才能解决 IHandler
而不是 ISpecificHandler
?
//Expect SpecificHandlerImpl as handler
IHandler handler = ServiceLocator.GetInstance<IHandler>(); //error
这会引发 InvalidOperationException
IHandler 类型未注册
有多种解决方案,但这实际上取决于您的应用程序真正需要什么。这里有一些建议。
您只需注册两次实现:
container.Register<IHandler, SpecificHandlerImpl>(Lifestyle.Scoped);
container.Register<ISpecificHandler, SpecificHandlerImpl>(Lifestyle.Scoped);
但也许您想解析多个处理程序,在这种情况下,您可能必须将它们注册为一个集合:
var reg1 = Lifestyle.Singleton.CreateRegistration<SpecificHandlerImpl>();
var reg2 = Lifestyle.Singleton.CreateRegistration<AnotherHandlerImpl>();
container.RegisterCollection<IHandler>(new[] { reg1, reg2 });
你可能 运行 但是当使用非通用 IHandler
接口时,你可能会遇到麻烦,因为你通常会有一个特定的实现应该在特定场景中执行(换句话说,你可能会违反 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 很好地解释了这种设计的优点。
但在不知道您要解决的问题的情况下,很难说什么是适合您的解决方案。