我想以这样一种方式装饰IService
,使得一些消费者会根据他们的类型选择特定的装饰器,如下所示:
container.Register<IService, Service>();
container.RegisterDecorator<IService, ServiceWithCaching>();
container.RegisterDecoratorConditional<IService, ServiceWithLogging>
(ctx => ctx.Consumer.ServiceType ==
typeof(IConsumerThatNeedsDecoratedService));
container.Register<IConsumerThatNeedsServiceWithLogging, Consumer1>();
container.Register<INormalConsumer, Consumer2>();
其中ServiceWithCaching
和ServiceWithLogging
在其构造函数中都使用IService
,包装一个IService实例,在内部调用它并执行其他操作(例如缓存,日志记录)。
Consumer1
和Consumer2
都在其构造函数中接受IService
。
我希望Consumer1
注入一个ServiceWithLogging
和Consumer2
ServiceWithCaching
的实例。期望的behvavior是Consumer1
将使用缓存结果的IService
实例,而Consumer2
将使用IService
的实例,两个缓存都会产生日志调用。< / p>
是否可以在Simple Injector中使用,如果没有任何已知的解决方法?
答案 0 :(得分:2)
您无法使用RegisterDecorator
执行此操作,但正如文档的Applying decorators conditionally based on consumer部分所述,您可以使用RegisterConditional
实现此目的:
container.RegisterConditional<IService, ServiceWithLogging>(
c => c.Consumer.ImplementationType == typeof(Consumer1));
container.RegisterConditional<IService, ServiceWithCaching>(
c => c.Consumer.ImplementationType != typeof(Consumer1)
&& c.Consumer.ImplementationType != typeof(ServiceWithCaching));
container.RegisterConditional<IService, Service>(c => !c.Handled);