使用以下通用存储库。
public interface IRepository<T> where T: class
{
void Commit();
void Delete(T item);
IQueryable<T> Find();
IList<T> FindAll();
void Add(T item);
}
如何编写结构图来使用它?我使用Structuremap v 2.6.1 for .net 3.5
public static void BootstrapStructureMap()
{
ObjectFactory.Initialize(x =>
{
// This is giving me problems!
x.For<IRepository<Employee>>().Use<IRepository<Employee>>();
});
}
我收到以下错误:
StructureMap异常代码202 没有为插件系列定义默认实例
答案 0 :(得分:2)
使用For().Use()
构造,当有人在Use
中请求类型时,告诉StructureMap实例化For
中给出的类型。通常,您为For
提供接口或抽象基类,因为您对抽象进行编程。
这里的问题是您将抽象类型(IRepository<T>
)传入Use
方法。 StructureMap将无法创建该接口的新实例。您需要创建IRepository<T>
(例如EntityFrameworkRepository<T>
)的通用实现并注册它。例如:
x.For<IRepository<Employee>>().Use<EntityFrameworkRepository<Employee>>();
然而,很快就会导致大量注册,因为您将拥有十几个要使用的存储库。因此,您可以使用开放泛型类型将其减少为单个注册,而不是为要使用的每个已关闭的通用存储库进行多次注册,如下所示:
x.For(typeof(IRepository<>)).Use(typeof(EntityFrameworkRepository<>)));