How to register repository pattern under configure service on startup class

asp.net-core-2.1 entity-framework-core

Question

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);
    }
}
1
1
1/17/2019 6:29:15 PM

Popular Answer

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)
0
1/17/2019 6:59:10 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow