2

我有一个非常简单的通用存储库:

public interface IRepository<TEntity, TNotFound>
    where TEntity : EntityObject
    where TNotFound : TEntity, new()
{
    IList<TEntity> GetAll();
    TEntity With(int id);
    TEntity Persist(TEntity itemToPersist);
    void Delete(TEntity itemToDelete);
}

我想为Term没有任何特殊行为的类型定义存储库的合同。所以它看起来像这样:

public class TermNotFound : Term
{ public TermNotFound() : base(String.Empty, String.Empty) { } }


public interface ITermRepository : IRepository<Term, TermNotFound> { }

现在为了测试,我想创建一个通用 repo 的内存实现,所以我有这个(为简洁起见未完成):

public class InMemoryRepository<TEntity, TNotFound> : IRepository<TEntity, TNotFound>
    where TEntity : EntityObject
    where TNotFound : TEntity, new()
{
    private IList<TEntity> _repo = new List<TEntity>();


    public IList<TEntity> GetAll()
    {
        return this._repo;
    }

    public TEntity With(int id)
    {
        return this._repo.SingleOrDefault(i => i.Id == id) ?? new TNotFound();
    }

    public TEntity Persist(TEntity itemToPersist)
    {
        throw new NotImplementedException();
    }

    public void Delete(TEntity itemToDelete)
    {
        throw new NotImplementedException();
    }
}

不难看出我希望它如何工作。对于我的测试,我希望InMemoryRepository注入通用实现来创建我的ITermRepository. 这有多难?

好吧,我不能让 StructureMap 去做。我曾尝试在扫描仪中使用WithDefaultConventionsConnectImplementationsToTypesClosing(typeof(IRepository<,>))但没有成功。

有人可以帮我吗?

4

1 回答 1

2

InMemoryRepository没有实现ITermRepository接口。这就是你无法连接它们的原因。

你可以用你所拥有的东西做的最好的事情就是InMemoryRepository<Term, TermNotFound>IRepository<Term, TermNotFound>.

如果你真的需要注入ITermRepository,那么你需要有另一个存储库类继承InMemoryRepository并实现ITermRepository

public class InMemoryTermRepository 
    : InMemoryRepository<Term, TermNotFound>, ITermRepository
{
}

现在您可以ITermRepository使用以下方式连接InMemoryTermRepository

.For<ITermRepository>().Use<InMemoryTermRepository>()

如果您有许多类似的接口ITermRepository,您可以创建一个 StructureMap 约定,以连接I...RepositoryInMemory...Repository. 默认约定是连接IClassClass.

于 2012-05-31T02:47:20.650 回答