我有一个非常简单的通用存储库:
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 来做这件事。我尝试过使用 WithDefaultConventions
和ConnectImplementationsToTypesClosing(typeof(IRepository<,>))
在扫描仪中没有成功。接下来我可以尝试什么?
最佳答案
您的InMemoryRepository
没有实现ITermRepository
界面。这就是您无法连接它们的原因。
你能用你所拥有的做的最好的事情就是注入(inject) InMemoryRepository<Term, TermNotFound>
对于 IRepository<Term, TermNotFound>
.
如果确实需要注入(inject)ITermRepository
,那么您需要有另一个继承自 InMemoryRepository
的存储库类并实现ITermRepository
:
public class InMemoryTermRepository
: InMemoryRepository<Term, TermNotFound>, ITermRepository
{
}
现在您可以连接 ITermRepository
至InMemoryTermRepository
使用:
.For<ITermRepository>().Use<InMemoryTermRepository>()
如果你有很多像ITermRepository
这样的接口(interface),您可以创建一个 StructureMap 约定来连接 I...Repository
至InMemory...Repository
。默认约定是连接 IClass
至Class
.
关于c# - 使用 StructureMap 连接不同的实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10812918/