2012-04-04 41 views
0

的高速緩存的實現我有一個服務接口,ICustomerService,並經兩種實現:城堡溫莎 - 註冊和解析緩存和相同的接口

public class CustomerService : ICustomerService 
{ 
    // stuff 
} 

public class CachedCustomerService : ICustomerService 
{ 
    public CachedCustomerService(CustomerService service) { } 
} 

緩存服務的話,只是緩存和代表正常服務。

對於註冊我已將ICustomerService解析爲CachedCustomerService,然後CustomerService僅針對其自己的類型註冊。

這工作正常。

我想知道的是,如果我可以使CachedCustomerService需要一個接口,而不是具體的CustomerService。原因是我們可能最終得到兩種類型的CustomerService,並且我想避免(如果可能)每個特定的緩存版本。

所以CachedCustomerService的構造函數將變爲:

public class CachedCustomerService : ICustomerService 
{ 
    // notice the ICustomerService 
    public CachedCustomerService(ICustomerService service) { } 
} 

我有過登記總量控制,但分辨率由asp.net的MVC的碗完成。

謝謝!

回答

3

所有你有溫莎城堡做的是像this article建議。 所以你的情況,你只需要以與您的緩存的業務先註冊你的客戶服務:

var container = new WindsorContainer() 
.Register(
Component.For(typeof(ICustomerService)).ImplementedBy(typeof(CachedCustomerService)), 
Component.For(typeof(ICustomerService)).ImplementedBy(typeof(CustomerService)) 
); 

然後緩存的客戶服務可以使用ICustomerService作爲內部/包裝的對象如下:

public class CachedCustomerService : ICustomerService 
{ 
    private ICustomerService _customerService; 
    public CachedCustomerService(ICustomerService service) 
    { 
     Console.WriteLine("Cached Customer service created"); 
     this._customerService = service; 
    } 

    public void Run() 
    { 
     Console.WriteLine("Cached Customer service running"); 
     this._customerService.Run(); 
    } 
} 

然後分辨率是正常的:

ICustomerService service = container.Resolve<ICustomerService>(); 
service.Run();