How to register Generic Repository pattern on startup class under configure service function ?
I try to register repository pattern on configure service function on startup.cs as below but i get error
InvalidOperationException: Unable to resolve service for type 'TabDataAccess.Repositories.RepositoryTab`1[TabDataAccess.Dto.Employee]' while attempting to activate 'WebTabCore.Controllers.EmployeeController'.
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped(typeof(IrepositoryTab<>), typeof(RepositoryTab<>));
services.AddDbContext<TabDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
Code details
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();
}
On EmployeeController public class EmployeeController : Controller {
private readonly IrepositoryTab<Employee> _repository;
public EmployeeController(RepositoryTab<Employee> emp)
{
this._repository = emp;
}
public IActionResult Index()
{
var employees = _repository.GetAll();
return View(employees);
}
}
You registered it in the service collection with:
services.AddScoped(typeof(IrepositoryTab<>), typeof(RepositoryTab<>));
Which quite literally means: "inject RepositoryTab<>
whenever IrepositoryTab<>
is requested." However, your controller takes RepositoryTab<>
in its constructor, and there's no service registration for RepositoryTab<>
itself. In other words, you need to change it to IrepositoryTab<>
instead:
public EmployeeController(IrepositoryTab<Employee> emp)