我有一个名为 的接口IXMLModelsRepository
,我有一个名为的具体实现XMLModelsRepository
,它只是从 XML 文件中读取。
但是,我想改进功能,并且我想将元素临时缓存到Dictionary<>
列表中。
我不想修改现有的XMLModelsRepository
,但我想创建一个在顶部添加缓存功能的新类。
如何使用Ninject
接口绑定到两个具体实现?
// the interface i am working with
public interface IXMLModelsRepository
{
Product GetProduct(Guid entity_Id);
}
// concrete implementation that reads from XML document
public class XMLModelsRepository : IXMLModelsRepository
{
private readonly XDocument _xDoc = LoadXMLDocument();
public Product GetProduct(Guid entity_Id)
{
return _xDoc.Element("root").Elements("Product").Where(p => p.Attribute("Entity_Id").Value == entity_Id.ToString();
}
}
// concrete implementation that is only responsable of caching the results
// this is the class that i will use in the project,
// but it needs a parameter of the same interface type
public class CachedXMLModelsRepository : IXMLModelsRepository
{
private readonly IXMLModelsRepository _repository;
public CachedXMLModelsRepository(
IXMLModelsRepository repository)
{
_repository = repository;
}
private readonly Dictionary<Guid, Product> cachedProducts = new Dictionary<Guid, Product>();
public Product GetProduct(Guid entity_Id)
{
if (cachedProducts.ContainsKey(entity_Id))
{
return cachedProducts[entity_Id];
}
Product product = _repository.GetProduct(entity_Id);
cachedProducts.Add(entity_Id, product);
return product;
}
}