ASP.NET Core supports the dependency injection (DI) software design pattern, which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies.
When the built-in dependency injection functionality is trying to create a type, it tries to resolve all of the constructor parameters. If it can’t resolve one of the parameters, it’ll throw a variation of exceptions, one of them is the following System.InvalidOperationException:
System.InvalidOperationException: Unable to resolve service for type 'MyProject.Models.Repository.IDataRepository`1[MyProject.Models.Employee]' while attempting to activate 'MyProject.Controllers.EmployeeController'
ASP.NET Core Error: System.InvalidOperationException
The simplest solution is to explicitly register the type. If that type has a primitive constructor parameter, then also tell it exactly how to create the type. This can be accomplished by adding registering this type in the ConfigureServices method in the Startup.cs as below:
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<MyDBContext>(options => options.UseSqlServer(Configuration["ConnectionString:MyDBConnectionString"]));
services.AddScoped<IDataRepository<Lead>, LeadManager>();
services.AddControllers();
}
Did you face this issue before? Please share your solution in the comments.