在Simple Injector中根据使用者服务类型注册装饰器条件

时间:2017-04-13 14:00:01

标签: c# dependency-injection decorator ioc-container simple-injector

我想以这样一种方式装饰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>();

其中ServiceWithCachingServiceWithLogging在其构造函数中都使用IService,包装一个IService实例,在内部调用它并执行其他操作(例如缓存,日志记录)。

Consumer1Consumer2都在其构造函数中接受IService

我希望Consumer1注入一个ServiceWithLoggingConsumer2 ServiceWithCaching的实例。期望的behvavior是Consumer1将使用缓存结果的IService实例,而Consumer2将使用IService的实例,两个缓存都会产生日志调用。< / p>

是否可以在Simple Injector中使用,如果没有任何已知的解决方法?

1 个答案:

答案 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);