Resolved- Unable to resolve service for type while attempting to activate
Issue description:
While using .NET API project and attempting to run application, it gives below error,
InvalidOperationException: Unable to resolve service for type 'IEmployeeRepository ' while attempting to activate 'EmployeeController'.
Sampel code which produces this error
Please refer this article for complete code
[Route("api/[controller]")]
[ApiController]
public class EmployeeController : ControllerBase
{
private readonly IEmployeeRepository _employeeRepository;
public EmployeeController(IEmployeeRepository employeeRepository)
{
_employeeRepository = employeeRepository;
}
// GET: api/Employee
[HttpGet]
public ActionResult<IEnumerable<Employee>> Get()
{
return Ok(_employeeRepository.GetEmployees());
}
// GET: api/Employee/5
[HttpGet("{id}")]
public ActionResult Get(int id)
{
return Ok(_employeeRepository.GetEmployeeByID(id));
}
Repository Interfaces was be defined as below,
public interface IEmployeeRepository
{
IEnumerable<Employee> GetEmployees();
Employee GetEmployeeByID(int employeeID);
}
Root cause and Issue resolution
The main reason for issue was found to be not registering the instance type correctly in the IOC contaier of API pipeline or middleware..
After adding the type and interface registration in the Container as below, the issue got resolved,
services.AddScoped<IEmployeeRepository, EmployeeRepository>();
Below is the complete sample code,
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddScoped<IEmployeeRepository, EmployeeRepository>();
services.AddDbContext<EmployeeContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("EmployeeDB"),
sqlServerOptionsAction: sqlOptions =>
{
sqlOptions.EnableRetryOnFailure();
});
});
}
If you are using .NET 6 and above framework please define the type as below,
builder.services.AddScoped<IEmployeeRepository, EmployeeRepository>();
Service lifetime can be defined using any the below approaches as below,
- Transient
- Scoped
- Singleton
Other possible root cause
Please ensure that you are injecting Interface in Controller and not the class type from Controller or other module where you want to use that type or service.
Example: Failed
private readonly IEmployeeRepository _employeeRepository;
public EmployeeController(EmployeeRepository employeeRepository)
{
_employeeRepository = employeeRepository;
}
Example: Working
private readonly IEmployeeRepository _employeeRepository;
public EmployeeController(IEmployeeRepository employeeRepository)
{
_employeeRepository = employeeRepository;
}
That’s all! Happy coding!
Does this help you fix your issue?
Do you have any better solutions or suggestions? Please sound off your comments below.
Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.