How to use nested interface implementations in Castle Windsor?

Suppose I have an interface for data extraction and its implementation:

interface IResourceProvider { string Get( Uri uri ); } class HttpResourceProvider : IResourceProvider { public string Get( Uri uri ) { // Download via HTTP. } } 

I can register this with Castle Windsor as follows:

 container.Register ( Component.For<IResourceProvider>().ImplementedBy<HttpResourceProvider>() ); 

(Everything is fine).

If I then decided that I needed a caching implementation as follows:

 class CachingResourceProvider : IResourceProvider { public CachingResourceProvider( IResourceProvider resourceProvider ) { _resourceProvider = resourceProvider; } public string Get( Uri uri ) { // Return from cache if it exists. // Otherwise use _resourceProvider and add to cache. } private readonly IResourceProvider _resourceProvider; } 

How can I register these nested dependencies? , i.e. I want to say that IResourceProvider is implemented by CachingResourceProvider , except where in the constructor, where is it HttpResourceProvider .

+4
source share
2 answers

Just register the CachingResourceProvider before the HttpResourceProvider - for example.

 container.Register(Component .For<IResourceProvider>() .ImplementedBy<CachingResourceProvider>()); container.Register(Component .For<IResourceProvider>() .ImplementedBy<HttpResourceProvider>()); 

BTW - This is known as the Decorator Design Template.

+5
source

This is known as a decorator pattern ...

See this link as an example: http://mikehadlow.blogspot.com/2010/01/10-advanced-windsor-tricks-4-how-to.html

+1
source

All Articles