'某些服务无法构建(验证服务描述符时出错'ServiceType:

问题描述 投票:0回答:1

我正在 .net 7 中创建一个应用程序,在图层模式、Apresetation、Application、Domain、Infra 中使用 dapper

.net 7 没有startup.cs 来进行注入,我在program.cs 中进行。

当我的服务(应用程序)调用我的域时,发生注入错误,但已经完成了。

程序.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();

服务

 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);
    }
}

我需要拨打这个电话

.net dapper
1个回答
0
投票

你这里有几个问题。

  1. 您没有消耗注入的依赖项。这才是正确的食用方法:
 public class FazerPedidoService : IFazerPedidoService
 {
     private readonly IFazerPedidoDomainService _fazerPedidoDomainService;

     // "Request" dependencies by passing them to the constructor
     // [optionally] then assign them to a private field
     public FazerPedidoService(IFazerPedidoDomainService fazerPedidoDomainService)
     {
_fazerPedidoDomainService = fazerPedidoDomainService;
     }

说明:

您正在

Program.cs
中正确注册依赖项,但您希望通过构造函数传递接口来“使用”接口(并将其分配给字段,以便可以在您的方法中重用)。这样,当您的服务首次访问/创建/调用(取决于范围)时,依赖项注入将查看您在
Program.cs
中完成的映射,并使用反射创建
IFazerPedidoDomainService
的实例。

注意:如果需要访问多个服务,只需将它们传递给构造函数并用逗号(,)分隔即可

  1. 您缺少一个依赖项(或者它被意外注释掉)。
// Uncomment this line
builder.Services.AddScoped<IFazerPedidoDomainService, FazerPedidoDomainService>();

说明: 您期望

IFazerPedidoDomainService
位于
FazerPedidoService
内,因此,您应该为它们两个进行依赖注入(似乎您曾经有过,您只是将其注释掉了)。


通过这些更改,它应该可以工作。

© www.soinside.com 2019 - 2024. All rights reserved.