So I'm trying to implement the concept of interception, while using autofac. I'm not doing anything fancy, like implementing dynamic interception, every class I have concrete code around.
My Code (not my real code, I found this online but it demonstrates my problem
public class DefaultProductService : IProductService
{
public Product GetProduct(int productId)
{
return new Product();
}
}
public class CachedProductService : IProductService
{
private readonly IProductService _innerProductService;
private readonly ICacheStorage _cacheStorage;
public CachedProductService(IProductService innerProductService, ICacheStorage cacheStorage)
{
if (innerProductService == null) throw new ArgumentNullException("ProductService");
if (cacheStorage == null) throw new ArgumentNullException("CacheStorage");
_cacheStorage = cacheStorage;
_innerProductService = innerProductService;
}
public Product GetProduct(int productId)
{
string key = "Product|" + productId;
Product p = _cacheStorage.Retrieve<Product>(key);
if (p == null)
{
p = _innerProductService.GetProduct(productId);
_cacheStorage.Store(key, p);
}
return p;
}
}
public class ProductManager : IProductManager
{
private readonly IProductService _productService;
public ProductManager(IProductService productService)
{
_productService = productService;
}
}
My problem is, I want my ProductManager to receive a "CachedProductService" for IProductService, and I want my CachedProductService to receive a "DefaultProductService" for IProductService.
I know of a few solutions, but none of them seem exactly correct. What is the right way of doing this?
Thanks! Michael

You can do this using named dependencies.
Instead of saying that the implementation of
IProductServiceisDefaultProductService, you'll have two implementations distinguished by their names, like this:There are a few different ways described in the documentation to indicate which implementation you want to inject into a given class. This looks like the simplest and most explicit:
To be honest, I don't like it because it causes the class to have a dependency on the container. It doesn't allow you to configure this completely separate from the classes themselves. With Windsor you would do this when registering dependencies with the container, telling it which named dependencies to use.
But this should work.