Suppose I have an interface for fetching data, and an implementation of it:
interface IResourceProvider
{
string Get( Uri uri );
}
class HttpResourceProvider : IResourceProvider
{
public string Get( Uri uri )
{
// Download via HTTP.
}
}
I can register this in Castle Windsor as follows:
container.Register
( Component.For<IResourceProvider>().ImplementedBy<HttpResourceProvider>()
);
(Which is all fine).
If I then decided I wanted 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 would I register these nested dependencies? i.e., I want to say an IResourceProvider is implemented by a CachingResourceProvider, except where in the constructor, where it’s a HttpResourceProvider.
Just register
CachingResourceProviderbeforeHttpResourceProvider– e.g.BTW – this is know as the Decorator design pattern.