2016-12-01 47 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>();