Ninject: 将接口绑定到多个实现

3

我有一个名为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;
    }
}

为什么你称它为 IXMLModelsRepository(带有 XML)?XML 不是消费者不应该关心的实现细节吗? - Steven
好的观点。模型始终来自一个XML文件,我将它们命名为XML模型,因为我还有业务模型,它们是数据库模型。 - Catalin
1个回答

5
您可以使用WhenInjectedExactlyInto结构。
kernel.Bind<IXMLModelsRepository >().To<CachedXMLModelsRepository>();
kernel.Bind<IXMLModelsRepository >().To<XMLModelsRepository>()
    .WhenInjectedExactlyInto(typeof(CachedXMLModelsRepository));

在上述示例中,Ninject将使用缓存的实例来查找接口,但在构建缓存的存储库时,它会注入非缓存对象。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接