具有 IoC 的代理设计模式

Proxy design pattern with IoC

我正在尝试为缓存服务实现代理设计模式,如下所示。

public interface IProductService
{
   int ProcessOrder(int orderId);
}

public class ProductService : IProductService
{
   public int ProcessOrder(int orderId)
   {
      // implementation
   }
}

public class CachedProductService : IProductService
{
   private IProductService _realService;

   public CachedProductService(IProductService realService)
   {
      _realService = realService;
   }

   public int ProcessOrder(int orderId)
   {
      if (exists-in-cache)
         return from cache
      else
         return _realService.ProcessOrder(orderId);
   }
}

我如何使用 IoC 容器 (Unity/Autofac) 创建真实的服务和缓存的服务对象,因为我可以将 IProductService 注册到 ProductServiceCachedProductServiceCachedProductService 又需要一个 IProductService 对象( ProductService) 在创建过程中。

我正在努力达到这样的目的:

应用程序将以 IProductService 为目标并为实例请求 IoC 容器,并且根据应用程序的配置(如果缓存是 enabled/disabled),应用程序将是提供 ProductServiceCachedProductService 实例。

有什么想法吗?谢谢

如果没有容器,您的图表将如下所示:

new CachedProductService(
    new ProductService());

下面是一个使用 Simple Injector 的例子:

container.Register<IProductService, ProductService>();

// Add caching conditionally based on a config switch
if (ConfigurationManager.AppSettings["usecaching"] == "true")
    container.RegisterDecorator<IProductService, CachedProductService>();