InvalidOperationException: невозможно разрешить службу для типа с EF dbcontext - PullRequest
0 голосов
/ 21 октября 2019

Я пытаюсь использовать Dependency Injection для контекста БД. Я не уверен, что я делаю неправильно, но даже после выполнения всех шагов, я все еще получаю ошибку

Ниже приведены шаги, которые я следую, подскажите, где происходит ошибка. Я использую многоуровневый проект, поэтому мои репозитории находятся на уровне доступа к БД, а контроллер в приложении API MVC

Мой класс контекста БД

   public partial class TestDbContext: DbContext  
    {

       public TestDbContext(DbContextOptions<TestDbContext> options)
           : base(options)
       {
       }

       public virtual DbSet<Table1> Table1{ get; set; }
    }

 public interface IRepository<T> where T : class
 {
       IQueryable<T> GetDbSet();
 }
 public class Repository<T> : IRepository<T> where T : class
   {
       protected DbContext _entities;
       protected readonly DbSet<T> _dbset;

       public Repository(DbContext context)
       {
           _entities = context;
           _dbset = context.Set<T>();
       }


       public virtual IQueryable<T> GetDbSet()
       {
           return _dbset;
       }
  }

pulbic interface IUserRepository
{
     List<UsersInfo> GetUsers();
}


public class UserRepository:IUserRepository
{
   private readonly IRepository<Table1> table1repo;
   public UserRepository(IRepository<Table1> _table1Repo)
   {
       table1repo = _table1Repo;
   }
   public List<UsersInfo> GetUsers()
   {
      return table1repo.GetDbSet().ToList();
   }
}

public class MyController : : ControllerBase
{
     private readonly IUserRepository _UserRepo;
      public MyController (IUserRepository UserRepo)
       {
           _UserRepo= clientInfo;
       }
       [HttpGet]
       public async Task<IActionResult> Get()
       {
           try
           {
               var result = _UserRepo.GetUsers();
               return new JsonResult(result) { SerializerSettings = new JsonSerializerSettings() { Formatting = Formatting.Indented } };
           }
           catch(Exception e)
           {
               throw e;
           }
       }

}

Startup.cs

public void ConfigureServices(IServiceCollection services)
       {
           services.AddSingleton<IConfiguration>(Configuration);
           services.Configure<IISOptions>(options =>
           {
               options.AutomaticAuthentication = false;
           });

           services.AddDbContext<TestDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("ConnectionString")));
           services.AddScoped<IUserRepository, UserRepository>();
           services.AddScoped(typeof(IRepository<>), typeof(Repository<>));
           services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
       }


1 Ответ

0 голосов
/ 21 октября 2019

Тип вашего контекста в вашем классе хранилища должен быть TestDbContext вместо DbContext.

public class Repository<T> : IRepository<T> where T : class
   {
       protected TestDbContext _entities;
       protected readonly DbSet<T> _dbset;

       public Repository(TestDbContext context)
       {
           _entities = context;
           _dbset = context.Set<T>();
       }


       public virtual IQueryable<T> GetDbSet()
       {
           return _dbset;
       }
  }
...