c# - 使用 StructureMap 连接不同的实现

标签 c# generics interface repository structuremap

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

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 类型的存储库定义契约(Contract)没有任何特殊行为。所以它看起来像这样:

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


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

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

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要注入(inject)的实现来创建我的 ITermRepository .

嗯,我无法让 StructureMap 来做这件事。我尝试过使用 WithDefaultConventionsConnectImplementationsToTypesClosing(typeof(IRepository<,>))在扫描仪中没有成功。接下来我可以尝试什么?

最佳答案

您的InMemoryRepository没有实现ITermRepository界面。这就是您无法连接它们的原因。

你能用你所拥有的做的最好的事情就是注入(inject) InMemoryRepository<Term, TermNotFound>对于 IRepository<Term, TermNotFound> .

如果确实需要注入(inject)ITermRepository ,那么您需要有另一个继承自 InMemoryRepository 的存储库类并实现ITermRepository :

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

现在您可以连接 ITermRepositoryInMemoryTermRepository使用:

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

如果你有很多像ITermRepository这样的接口(interface),您可以创建一个 StructureMap 约定来连接 I...RepositoryInMemory...Repository 。默认约定是连接 IClassClass .

关于c# - 使用 StructureMap 连接不同的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10812918/

相关文章:

c# - VB.NET 和 sizeof

Java - Collection.Sort 接口(interface)对象

java - 如何使用 lambda 在 Java 中实现两个抽象方法?

pointers - 获取通过接口(interface)获取的 var 上的指针

c# - 用于类型推断的通用身份函数

java - 在另一个默认方法中从其他接口(interface)调用默认方法

c# - Stream Seek 功能未按预期使用react

c# - 使用 Linq 和 Guid 的匿名类型

c# - OpenGL 中的纹理显示为单色

C# 泛型继承数据访问