![](/img/trans.png)
[英]Could not create an instance of type . Type is an interface or abstract class and cannot be instantiated
[英]Cannot create an instance of the abstract class or interface interface with type
我知道这个错误是什么,我的问题略有不同。
这是这些大脑衰落的时刻之一。
我一直在阅读有关存储库和工作单元模式的这篇有趣的文章:
我正在使用此代码,现在尝试对其进行调整,以便可以将IoC与DI一起使用。
现在,这是我刚刚陷入精神空白的地方。
我将所有类更改为使用接口等。因此,给出以下代码片段:
public class UnitOfWork : IDisposable
{
private SchoolContext context = new SchoolContext();
private GenericRepository<Department> departmentRepository;
private GenericRepository<Course> courseRepository;
public GenericRepository<Department> DepartmentRepository
{
get
{
if (this.departmentRepository == null)
{
this.departmentRepository = new GenericRepository<Department>(context);
}
return departmentRepository;
}
}
}
}
我如何编辑此行:
this.departmentRepository = new GenericRepository<Department>(context);
因此,我不必引用实际的类,因此可以确保将其解耦并避免产生语法错误:
Cannot create an instance of the abstract class or interface interface with type
提前谢谢了!
简单地说,你应该声明域作为一个接口类型。 该接口可以具有类似于IGenericRepository<T>
的名称。 那么类GenericRepository<T>
应实现该接口。 然后,您在IoC框架中注册该类,该类基本上告诉该框架:“当我请求该接口的实例时,请给我该类的实例”。 然后,您可以执行以下操作:
this.departmentRepository = InversionOfControl.Resolve<IGenericRepository<Department>>();
(resolve方法的签名类似于public T Resolve<T>()
)
似乎GenericRepository是无法实例化的抽象类。
http://msdn.microsoft.com/zh-CN/library/sf985hc5(v=vs.71).aspx
您需要派生类为GenericRepository,即
DepartmentRepository : GenericRepository<Department>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.