如何在配置服务功能下在启动类上注册通用存储库模式?
我尝试在startup.cs的configure service功能上注册存储库模式,如下所示,但出现错误
InvalidOperationException:在尝试激活“ WebTabCore.Controllers.EmployeeController”时,无法解析类型为“ TabDataAccess.Repositories.RepositoryTab`1 [TabDataAccess.Dto.Employee]”的服务。
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped(typeof(IrepositoryTab<>), typeof(RepositoryTab<>));
services.AddDbContext<TabDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
代码详细信息
public class Employee
{
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
}
public class TabDbContext : DbContext
{
public TabDbContext(DbContextOptions<TabDbContext> options)
: base(options)
{ }
public DbSet<Employee> Employees { get; set; }
}
public class RepositoryTab : IrepositoryTab where T : class
{
protected TabDbContext db { get; set; }
private DbSet dbSet;
public RepositoryTab(TabDbContext Tabdb)
{
db = Tabdb;
dbSet = db.Set();
}
public IEnumerable GetAll()
{
return dbSet.ToList();
}
}
public interface IrepositoryTab where T : class
{
IEnumerable GetAll();
}
在EmployeeController上 公共类EmployeeController:控制器 {
private readonly IrepositoryTab<Employee> _repository;
public EmployeeController(RepositoryTab<Employee> emp)
{
this._repository = emp;
}
public IActionResult Index()
{
var employees = _repository.GetAll();
return View(employees);
}
}
答案 0 :(得分:0)
您通过以下方式将其注册在服务集中:
services.AddScoped(typeof(IrepositoryTab<>), typeof(RepositoryTab<>));
从字面上讲,这意味着:“每当请求RepositoryTab<>
时注入IrepositoryTab<>
。”但是,您的控制器将RepositoryTab<>
用作其构造函数,并且RepositoryTab<>
本身没有任何服务注册。换句话说,您需要将其更改为IrepositoryTab<>
:
public EmployeeController(IrepositoryTab<Employee> emp)