C# 无法创建类型为的抽象类或接口的实例
我知道这个错误是什么,我的问题略有不同 这是大脑衰退的时刻之一 我一直在读这篇关于Repositoy和工作单元模式的有趣文章: 我正在玩这段代码,现在我正在尝试调整它,这样我就可以在DI中使用IoC了 现在,这里是我刚刚遇到的一个心理空白 我正在将所有类更改为使用接口等。因此给出以下代码片段:C# 无法创建类型为的抽象类或接口的实例,c#,interface,C#,Interface,我知道这个错误是什么,我的问题略有不同 这是大脑衰退的时刻之一 我一直在读这篇关于Repositoy和工作单元模式的有趣文章: 我正在玩这段代码,现在我正在尝试调整它,这样我就可以在DI中使用IoC了 现在,这里是我刚刚遇到的一个心理空白 我正在将所有类更改为使用接口等。因此给出以下代码片段: public class UnitOfWork : IDisposable { private SchoolContext context = new SchoolCon
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;
}
}
}
}
非常感谢 简而言之,您应该将字段声明为接口类型。接口的名称可能类似于
IGenericRepository
。然后类GenericRepository
应该实现该接口。然后用IoC框架注册这个类,它基本上告诉这个框架,“当我请求这个接口的实例时,给我一个该类的实例”。然后你可以这样做:
this.departmentRepository = InversionOfControl.Resolve<IGenericRepository<Department>>();
this.departmentRepository=InversionOfControl.Resolve();
(解析方法有一个签名,如public T resolve()
)
似乎GenericRepository是无法实例化的抽象类
您需要GenericRepository的派生类,即
DepartmentRepository : GenericRepository<Department>
DepartmentRepository:GenericRepository
this.departmentRepository = InversionOfControl.Resolve<IGenericRepository<Department>>();
DepartmentRepository : GenericRepository<Department>