Reputation: 1
Good afternoon, I created my interface in my asp net core mvc 6 project. I use this interface in the EmployeeController controller, when I try to go to the view that implements my controller, I get this error. Do not tell me what is the problem?
Interfaces:
namespace WebProductionAccounting.DAL.Interfaces
{
public interface IBaseRepository<T>
{
bool Create(T entity);
T GetValue(int id);
Task<List<T>> GetAll();
bool Delete(T entity);
}
}
using WebProductionAccounting.Domain.Entities;
namespace WebProductionAccounting.DAL.Interfaces
{
public interface IEmployeeRepository:IBaseRepository<Employee>
{
Employee GetByFullname(string firstname,string lastname,string middlename);
}
}
Controller:
using Microsoft.AspNetCore.Mvc;
using WebProductionAccounting.DAL.Interfaces;
namespace WebProductionAccounting.Controllers
{
public class EmployeeController : Controller
{
private readonly IEmployeeRepository _employeeRepository;
public EmployeeController(IEmployeeRepository employeeRepository)
{
_employeeRepository = employeeRepository;
}
[HttpGet]
public async Task<IActionResult> GetEmployees()
{
var response = await _employeeRepository.GetAll();
return View(response);
}
}
}
Program.cs:
using Microsoft.EntityFrameworkCore;
using WebProductionAccounting.DAL;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
// Get connection with pssql db
var connection = builder.Configuration.GetConnectionString("DefaultConnection");
// Reg DbConext pssql
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseNpgsql(connection));
// Add Npgsql.EnableLegacyTimestampBehavior and Npgsql.DisableDateTimeInfinityConversions in DbContext
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);
AppContext.SetSwitch("Npgsql.DisableDateTimeInfinityConversions", true);
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
app.UseExceptionHandler("/Home/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.MapControllerRoute(
name: "default",
pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();
When going to the GetEmployees view in my web application, an error occurs:
InvalidOperationException: Unable to resolve service for type 'WebProductionAccounting.DAL.Interfaces.IEmployeeRepository' while attempting to activate 'WebProductionAccounting.Controllers.EmployeeController'.
Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired)
Tried to register services through AddTransient,AddScoped but did not understand where exactly to register in my main project file.
Upvotes: 0
Views: 94
Reputation: 22515
InvalidOperationException: Unable to resolve service for type 'WebProductionAccounting.DAL.Interfaces.IEmployeeRepository' Microsoft.Extensions.DependencyInjection.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, bool isDefaultParameterRequired).Tried to register services through AddTransient,AddScoped but did not understand where exactly to register in my main project file.
Well, the error you are getting is pretty obvious and straight forward. As you are learning so let me explain more details reagrding your exception.
If you would seen the exception message, its pointing you that you haven't register IEmployeeRepository interface because you are trying to inject IEmployeeRepository within your EmployeeController.
Why The Exception For:
In asp.net core you might hear a concept Dependency injection which is a technique for achieving Inversion of Control (IoC) between classes and their dependencies.
What's more is, while you are creating any service class for your scenario the EmployeeRepository you need to tell the compiler to build that service. In asp.net core we call it to register a service that's is in program.cs we need to AddScoped
for your EmployeeRepository.
Register Your Dependency:
So to resolve your exception you can write as following:
builder.Services.AddScoped<IEmployeeRepository, EmployeeRepository>();
Output:
Note: As you can observe in above example I have reproduce your exception, I have IUnitOfWork service interface. However, I haven't resgiter that in program.cs file consequently, I got the error. You can see below:
If you would like to know more details on dependency inject and service life time you could check our official document here.
Upvotes: 0
Reputation: 72
Add the following class
public class EmployeeRepository : IEmployeeRepository
{
public bool Create(Employee entity)
{
throw new NotImplementedException();
}
public bool Delete(Employee entity)
{
throw new NotImplementedException();
}
public Task<List<Employee>> GetAll()
{
throw new NotImplementedException();
}
public Employee GetByFullname(string firstname, string lastname, string middlename)
{
throw new NotImplementedException();
}
public Employee GetValue(int id)
{
throw new NotImplementedException();
}
}
and then After implementing the methods,add
builder.Services.AddScoped<IEmployeeRepository, EmployeeRepository>();
in program.cs
Upvotes: 1