InvalidOperationException в ASP. NET Core MVC в браузере - PullRequest
0 голосов
/ 31 марта 2020

У меня есть ASP. NET Core MVC приложение, которое использует Entity Framework Core O / RM. Я реализую шаблон репозитория generi c в моем приложении. Есть две сущности, 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 class-

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>();
    } 

    //... 
}

Program.cs -

public static void Main(string[] args)
{
    CreateHostBuilder(args).Build().Run();
}

StartUp. 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]'. Убедитесь, что тип является конкретным, а службы зарегистрированы для всех параметров конструктора publi c. Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateConstructorCallSite (время жизни ResultCache, тип serviceType, тип creationType, CallSiteChain callSiteChain)

Я не могу понять исключение, я не знаю, что я делаю здесь не так. Я знаю, что вставил много кода, но даже не знаю, как объяснить исключение.

1 Ответ

0 голосов
/ 31 марта 2020

В соответствии с исключением, я уверен, что ваша программа не может создать экземпляр GenericRepository.

Это связано с тем, что GenericRepository зависит от вашего EmployeeDepartmentDetail, который является вашим DbContext из EntityFramework Core. И этот DbContext не был зарегистрирован в вашем Io C контейнере.

У меня было точно такое же исключение, как и у вас, после того как я отключил регистрацию службы для моего DbContext. Пожалуйста, обратитесь к скриншоту по следующей ссылке: введите описание изображения здесь

Чтобы устранить это исключение, давайте зарегистрируем ваш DbContext или EmployeeDepartmentDetail в вашем контейнере Io C, проверив ваш Startup .cs -> ConfigureServices и добавил что-то вроде этого:

services.AddDbContext<SchoolContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
...