3

と呼ばれるインターフェースがあり、XMLファイルから単純に読み取るIXMLModelsRepositoryという具体的な実装があります。XMLModelsRepository

しかし、機能を改善したいので、要素を一時的にDictionary<>リストにキャッシュしたいです。

既存の を変更したくありませんXMLModelsRepositoryが、キャッシング機能を追加する新しいクラスを作成したいと考えています。

Ninjectインターフェイスを使用して 2 つの具体的な実装にバインドするにはどうすればよいですか?

// 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;
    }
}
4

1 に答える 1

5

WhenInjectedExactlyIntoコンストラクトを使用できます。

kernel.Bind<IXMLModelsRepository >().To<CachedXMLModelsRepository>();
kernel.Bind<IXMLModelsRepository >().To<XMLModelsRepository>()
    .WhenInjectedExactlyInto(typeof(CachedXMLModelsRepository));

上記の例では、Ninject はインターフェイスのすべてのルックアップにキャッシュされたインスタンスを使用しますが、キャッシュされたリポジトリを構築するときに、キャッシュされていないオブジェクトを挿入します。

于 2013-09-27T10:29:58.173 に答える