I'm creating an application in .net 7, using dapper in the layers pattern, Apresetation, Application, Domain, Infra
.net 7 doesn't have startup.cs to do the injections, I'm doing them in program.cs.
when my service (Application) calls my Domain, the injection error occurs, but it has been done.
Program.cs
using Ecommerce.Application.Services;
using Ecommerce.Application.Services.Interfaces;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddControllers();
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddScoped<IFazerPedidoService, FazerPedidoService>();
//builder.Services.AddScoped<IFazerPedidoDomainService, FazerPedidoDomainService>();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseAuthorization();
app.MapControllers();
app.Run();
Sevice
public class FazerPedidoService : IFazerPedidoService
{
private readonly IFazerPedidoDomainService _fazerPedidoDomainService;
public FazerPedidoService()
{
}
public FazerPedidoModel FazerPedido(FazerPedidoModel fazerPedidoModel)
{
var pedido = new FazerPedidoEntity
{
Id = 999
};
pedido = _fazerPedidoDomainService.FazerPedidoDomain(pedido);
return fazerPedidoModel;
}
}
namespace Ecommerce.Domain.Interfaces
{
public interface IFazerPedidoDomainService
{
public FazerPedidoEntity FazerPedidoDomain(FazerPedidoEntity fazerPedidoEntity);
}
}
I need to make this call
Well no, they are not OK.
As I mentioned, you must ensure that you inject all of your services, at any level, not just the top level one.
Instead of
builder.Services.AddSingleton<IFazerPedidoService, FazerPedidoService>();
Do this:
builder.Services.AddSingleton<IFazerPedidoService, FazerPedidoService>();
builder.Services.AddSingleton<IFazerPedidoDomainService, FazerPedidoDomainService>();
// Assuming you have FazerPedidoRepository class here
builder.Services.AddSingleton<IFazerPedidoRepository, FazerPedidoRepository >();
(And change them back to AddScoped()
, it should work perfectly fine)
Explanation:
Look at how you are injecting the IFazerPedidoService
. There are 2 steps:
Program.cs
You need to follow the same pattern for any other service you have, regardless of where you are consuming it (i.e. controller or other injected service).
In your case C# DI (dependency injection) has no clue how to 'enable' the IFazerPedidoService
, because it cannot recognize the IFazerPedidoDomainService
, which cannot recognize the IFazerPedidoRepository
. Do you see the pattern?
Inject all the way down, all the necessary services and it will work.