[英]InvalidOperationException in ASP.NET Core MVC in Browser
我有一个使用 Entity Framework Core O/RM 的 ASP.NET Core MVC 应用程序。 我正在我的应用程序中实现通用存储库模式。 有两个实体, Employee
和Department
。 有一个上下文类EmployeeDepartmentDetails
。有一个接口IGenericRepository
由GenericRepository
实现。 GenericRepository
有一个EmployeeDepartmentDetails
的依赖注入。我的控制器EmployeeController
有一个IGenericRepository
的依赖注入。
IGenericRepository.cs -
public interface IGenericRepository<TEntity> where TEntity : class
{
//...
}
EmployeeDepartmentDetail.cs
public class EmployeeDepartmentDetail : DbContext
{
public DbSet<Employee> Employees { get; set; }
public DbSet<Department> Department { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(@"Server=JARVIS\SQLEXPRESS;Database=EmpDep;Trusted_Connection=True;");
}
protected override void OnModelCreating(ModelBuilder builder)
{
base.OnModelCreating(builder);
}
}
GenericRepository.cs - 这里EmployeeDepartmentDetails
是我的上下文类,它继承了DBContext
类 -
public class GenericRepository<TEntity> :IGenericRepository<TEntity> where TEntity : class
{
DbSet<TEntity> _dbSet;
// Dependency Injection
private readonly EmployeeDepartmentDetail _employeeDepartmentDetail;
public GenericRepository(EmployeeDepartmentDetail employeeDepartmentDetail)
{
_employeeDepartmentDetail = employeeDepartmentDetail;
_dbSet = _employeeDepartmentDetail.Set<TEntity>();
}
//...
}
程序.cs -
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
启动.cs -
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddScoped(typeof(IGenericRepository<>), typeof(GenericRepository<>));
}
EmployeeController.cs -
public class EmployeeController : Controller
{
private readonly IGenericRepository<Employee> _genericRepository;
public EmployeeController(IGenericRepository<Employee> genericRepository)
{
_genericRepository = genericRepository;
}
//...
}
当我运行我的应用程序时,我在浏览器中收到此异常 -
InvalidOperationException:找不到适合类型“InfrastructureLayer.GenericRepository.Implementation.GenericRepository`1[Entities.Employee]”的构造函数。 确保类型是具体的,并且为公共构造函数的所有参数注册了服务。 Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite(ResultCache 生存期,类型 serviceType,类型 implementationType,CallSiteChain callSiteChain)
我无法理解异常,我不知道我在这里做错了什么。 我知道我粘贴了很多代码,但我什至不知道如何解释异常。
根据例外情况,我确定您的程序无法实例化 GenericRepository。
这是因为 GenericRepository 依赖于您的 EmployeeDepartmentDetail,它是来自 EntityFramework Core 的 DbContext。 而这个 DbContext 还没有注册到你的 IoC 容器。
在禁用 DbContext 的服务注册后,我遇到了与您完全相同的异常。 请参考以下链接中的截图:在此输入图片描述
为了解决这个异常,让我们通过检查您的 Startup.cs -> ConfigureServices 并添加如下内容将您的 DbContext 或 EmployeeDepartmentDetail 注册到您的 IoC 容器:
services.AddDbContext<SchoolContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.