gpt4 book ai didi

c# - (接口(interface))检测到类型服务的循环依赖

转载 作者:行者123 更新时间:2023-12-05 09:09:40 27 4
gpt4 key购买 nike

我有 2 个接口(interface):

public interface IPedidoService
{
UsuarioDrogueria CUsuarioDrogueria(string userId, int idDrogueria);
List<PedidoComboProducto> CPedidosCombosProductos(int idcombo, int idPedido);
}

public interface IEmailService
{
void SendEmailAttachment(string email, string subject, string archive);
void SendNotificationEmail(List<Pedido> pedidos, string email, Drogueria drog);
void SendNotificationEmailADM(Pedido pedido) ;
}

我想在 IPedidoService 中使用 IEmailService 的函数,所以我在创建存储库时将它注入(inject)到它的构造函数中。

public class PedidoService : IPedidoService
{
private readonly IEmailService emailService;

public PedidoService(IEmailService e)
{
this.emailService = e;
}
}

到这里为止一切正常,但是当我尝试反转角色时(IEmailService 中的IPedidoService 函数):

public class EmailService : IEmailService
{
private readonly IPedidoService pedidoSettings;

public EmailService(IPedidoService p)
{
this.pedidoSettings = p;
}
}

我最终得到这个异常:

System.InvalidOperationException: A circular dependency was detected for the service of type
'EnvioPedidos.Data.Abstract.IPedidoService'.
EnvioPedidos.Data.Abstract.IPedidoService(EnvioPedidos.PedidoService) ->
EnvioPedidos.Data.Abstract.IEmailService(EnvioPedidos.EmailService) ->
EnvioPedidos.Data.Abstract.IPedidoService

谁能帮我追踪这里的问题?

最佳答案

一个简单的方法是使用 Lazy<T>基于此 blog 的类:

自定义扩展方法:

public static class LazyResolutionMiddlewareExtensions
{
public static IServiceCollection AddLazyResolution(this IServiceCollection services)
{
return services.AddTransient(
typeof(Lazy<>),
typeof(LazilyResolved<>));
}
}

public class LazilyResolved<T> : Lazy<T>
{
public LazilyResolved(IServiceProvider serviceProvider)
: base(serviceProvider.GetRequiredService<T>)
{
}
}

在 Startup.cs 中配置:

public void ConfigureServices(IServiceCollection services)
{
//services.AddSingleton<IPedidoService, PedidoService>();
//services.AddSingleton<IEmailService, EmailService>();

services.AddLazyResolution();
}

更改您的工具类:

public class PedidoService : IPedidoService
{
private readonly Lazy<IEmailService> emailService;

public PedidoService(Lazy<IEmailService> e)
{
this.emailService = e;
}

//...
}
public class EmailService : IEmailService
{
private readonly Lazy<IPedidoService> pedidoSettings;

public EmailService(Lazy<IPedidoService> p)
{
this.pedidoSettings = p;
}
//...
}

关于c# - (接口(interface))检测到类型服务的循环依赖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62217815/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com