2

I am following this article: https://code-maze.com/net-core-web-api-ef-core-code-first/ to set up my backend using .NET 6.0 (in article they are using 5).

I am getting this error on Postman (trying to test the API):

System.InvalidOperationException: Unable to resolve service for type 'codeFirstExample.Models.Repository.IDataRepository`1[codeFirstExample.Models.Employee]' while attempting to activate 'codeFirstExample.Controllers.EmployeeController'

This is my code:

Model (Employee.cs):

namespace codeFirstExample.Models
{
    public class Employee
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public long EmployeeId { get; set; } 
        public string FirstName { get; set; } = string.Empty;
        public string LastName { get; set; } = string.Empty;
        public string PhoneNumber { get; set; } = string.Empty;
        public string Email { get; set; } = string.Empty;
    }
}

DbContext (EmployeeContext.cs):

namespace codeFirstExample.Models
{
    public class EmployeeContext : DbContext
    {
        private readonly IConfiguration Configuration;

        public EmployeeContext(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<EmployeeContext>(opts => opts.UseSqlServer(Configuration["ConnectionString:EmployeeDB"]));
            services.AddScoped<IDataRepository<Employee>, EmployeeManager>();
            services.AddControllers();
        }

        protected override void OnConfiguring(DbContextOptionsBuilder options)
        {
            // connect to sql server with connection string from app settings
            options.UseSqlServer(Configuration.GetConnectionString("EmployeeDB"));
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Employee>().HasData(new Employee
            {
                EmployeeId = 1,
                FirstName = "Uncle",
                LastName = "Bob",
                Email = "uncle.bob@gmail.com",
                PhoneNumber = "999-888-7777"
            }, new Employee
            {
                EmployeeId = 2,
                FirstName = "Jan",
                LastName = "Kirsten",
                Email = "jan.kirsten@gmail.com",
                PhoneNumber = "111-222-3333"
            });
        }

        public DbSet<Employee> Employees => Set<Employee>();


    } 
}

Repository (IDataRepository.cs):

namespace codeFirstExample.Models.Repository
{
    public interface IDataRepository<TEntity>
    {
        IEnumerable<TEntity> GetAll();
        TEntity Get(long id);
        void Add(TEntity entity);
        void Update(TEntity dbEntity, TEntity entity);
        void Delete(TEntity entity);
    }
}

Controller (EmployeeController.cs):

namespace codeFirstExample.Controllers
{
    [Route("api/employee")]
    [ApiController]
    public class EmployeeController : ControllerBase
    {
        private readonly IDataRepository<Employee> _dataRepository;
        public EmployeeController(IDataRepository<Employee> dataRepository, EmployeeContext context)
        {
            _dataRepository = dataRepository;
        }
        // GET: api/Employee
        [HttpGet]
        public IActionResult Get()
        {
            IEnumerable<Employee> employees = _dataRepository.GetAll();
            return Ok(employees);
        }
        // GET: api/Employee/5
        [HttpGet("{id}", Name = "Get")]
        public IActionResult Get(int id)
        {
            Employee employee = _dataRepository.Get(id);
            if (employee == null)
            {
                return NotFound("The Employee record couldn't be found.");
            }
            return Ok(employee);
        }
        // POST: api/Employee
        [HttpPost]
        public IActionResult Post([FromBody] Employee employee)
        {
            if (employee == null)
            {
                return BadRequest("Employee is null.");
            }
            _dataRepository.Add(employee);
            return CreatedAtRoute(
                  "Get",
                  new { Id = employee.EmployeeId },
                  employee);
        }
        // PUT: api/Employee/5
        [HttpPut("{id}")]
        public IActionResult Put(int id, [FromBody] Employee employee)
        {
            if (employee == null)
            {
                return BadRequest("Employee is null.");
            }
            Employee employeeToUpdate = _dataRepository.Get(id);
            if (employeeToUpdate == null)
            {
                return NotFound("The Employee record couldn't be found.");
            }
            _dataRepository.Update(employeeToUpdate, employee);
            return NoContent();
        }
        // DELETE: api/Employee/5
        [HttpDelete("{id}")]
        public IActionResult Delete(int id)
        {
            Employee employee = _dataRepository.Get(id);
            if (employee == null)
            {
                return NotFound("The Employee record couldn't be found.");
            }
            _dataRepository.Delete(employee);
            return NoContent();
        }
    }
}

I'm not sure whats going wrong, so can anybody help me with this?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
sphcstrs
  • 25
  • 4
  • You need to add the dbcontext and other services to the service container in startup. It’s mentioned in the article you linked – Lee Apr 29 '22 at 13:18

1 Answers1

0

Add your services in the ConfigureServices method in the Startup.cs as below:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<EmployeeContext>(opts => opts.UseSqlServer(Configuration["ConnectionString:EmployeeDB"]));
    services.AddScoped<IDataRepository<Employee>, EmployeeManager>();
    services.AddControllers();
}
Lee
  • 703
  • 6
  • 20
  • Thanks for you answer! Since I am using ASP.NET 6.0 there is no startup.cs, instead I added this code to my program.cs but I get this error: The name 'Configuration' does not exist in the current context'. – sphcstrs Apr 29 '22 at 13:29
  • 1
    Please see this answer on how to access configuration in .net 6 https://stackoverflow.com/questions/69722872/asp-net-core-6-how-to-access-configuration-during-startup – Lee Apr 29 '22 at 13:31