C# 使用StructureMap连接不同的实现

C# 使用StructureMap连接不同的实现,c#,generics,interface,repository,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);

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

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);
}
现在,为了进行测试,我想创建一个通用repo的内存内实现,因此我有以下内容(为简洁起见,尚未完成):

MemoryRepository中的公共类:IRepository
其中tenty:EntityObject
其中TNotFound:TEntity,new()
{
私有IList_repo=新列表();
公共IList GetAll()
{
归还此文件;
}
具有(int id)的公共TEntity
{
返回此值。_repo.SingleOrDefault(i=>i.Id==Id)??new TNotFound();
}
公共tenty Persist(tenty itemToPersist)
{
抛出新的NotImplementedException();
}
公共作废删除(TEntity itemToDelete)
{
抛出新的NotImplementedException();
}
}
不难看出我希望它如何工作。对于我的测试,我希望注入通用的
InMemoryRepository
实现来创建我的
ITermRepository
。这有多难

嗯,我不能让StructureMap来做。我曾尝试在扫描仪中使用带有默认约定的
连接实现到类型关闭(typeof(IRepository))
,但没有成功


有人能帮我一下吗?

您的
内存存储库
没有实现
ITermRepository
接口。这就是为什么你不能连接它们

使用现有的内容,您可以做的最好的事情是为
IRepository
注入
InMemoryRepository

如果确实需要注入
ITermRepository
,则需要从
InMemoryRepository
继承另一个存储库类,并实现
ITermRepository

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

如果您有许多接口,如
ITermRepository
,您可以创建一个StructureMap约定,将
I…Repository
连接到
InMemory…Repository
。默认约定是将
IClass
连接到
Class

自从我上次使用SM已经有几年了,所以不打算发布答案,但是GetNamedInstance是否满足您的要求?我还相信,您可以在本地覆盖接口的配置解析,但我不记得它在api中的位置。嗨,David。谢谢你的回复。我不认为
GetNamedInstance
会对我有所帮助-在这个阶段,我不会在容器中命名实例。我认为,当你有许多相同的实例用于不同的用途时,你就会这样做。我现在只想要一个
ITermRepository
实例,它只是在创建它,这让我陷入了困境。我认为您提到的另一个选项是
IRegistrationConvention
,但我正在考虑是否可以首先避免这种情况。我认为您有一个测试实现(使用内存中的repo)和一个生产实现,不是吗?我通常从不使用我的ioc容器进行测试,我更喜欢手工连接测试夹具,但如果你使用容器,我会说你可以使用命名实例进行测试。我明白你的意思,但我仍然不认为这能满足我的需要。这并不是让不同的实例用于不同的用途(测试、生产等)。SM无法根据我提供的配置创建
ITermRepository
。我需要有人告诉我如何获得正确的配置,以便SM知道如何构建
ITermRepository
。再次感谢汉克斯。昨天某个时候,我在看界面时,与你的开场白一样意识到了这一点。我想我的思想走了一条c#无法走的路。谢谢你帮我澄清,没问题。很乐意帮忙。
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();
    }
}
public class InMemoryTermRepository 
    : InMemoryRepository<Term, TermNotFound>, ITermRepository
{
}
.For<ITermRepository>().Use<InMemoryTermRepository>()