2016-12-01 49 views
0

我正在尝试实现代理设计模式的缓存服务如下。代理设计模式与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容器(团结/ Autofac)创造真正的服务和缓存的服务对象,我可以注册IProductServiceProductServiceCachedProductServiceCachedProductService又需要IProductService object(ProductService)在创建期间。

我想在这样的事情来:

应用程序将目标IProductService并要求IoC容器的一个实例,并根据应用的配置(如果缓存启用/禁用)时,应用程序将提供ProductServiceCachedProductService实例。

任何想法?谢谢。

回答

0

无容器您的图形应该是这样的:

new CachedProductService(
    new ProductService()); 

下面是一个使用简单的喷油器的例子:

container.Register<IProductService, ProductService>(); 

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