“检测到 Autofac 圆形组件依赖性"错误 [英] 'Autofac Circular Component Dependency Detected' Error

查看:31
本文介绍了“检测到 Autofac 圆形组件依赖性"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 IoC 的新手,正在我当前的项目中使用 Autofac.

I am new to IoC and am using Autofac in my current project.

我有以下两个类:

public class UserService : IUserService
{
    private readonly IUserRepository _repo;
    private readonly IMailService _mailService;
    public UserService(IUserRepository repo, IMailService mailService)
    {
        _repo = repo;
        _mailService = mailService;
    }
}

public class MailService : IMailService
{
    private readonly IMailRepository _repo;
    private readonly IUserService _userService;
    public MailService(IMailRepository repo, IUserService userService)
    {
        _repo = repo;
        _userService = userService;
    }
}

最初,我的 UserService 类不需要 MailService 类的实例,但现在需要了,自从将其引入 UserService 构造函数后,就出现了这种循环依赖错误,作为新手,我不是确定如何解决这个问题.

Initially, my UserService class didn't require an instance of the MailService class, but now it does, and it's since introducing this into the UserService Constructor that this circular dependency error has arisen, and being a newbie, I'm not sure how to resolve this.

这是我目前在 Autofac 中注册的课程的方式:

This is how my classes are currently registered in Autofac:

var builder = new ContainerBuilder();

// controllers                      
builder.RegisterControllers(Assembly.GetAssembly(typeof(UsersController)));

// register other classes
builder.RegisterType<UserRepository>().As<IUserRepository>();
builder.RegisterType<MailRepository>().As<IMailRepository>();
builder.RegisterType<UserService>().As<IUserService>();
builder.RegisterType<MailService>().As<IMailService>();

推荐答案

如果一个 UserService 需要一个 IMailService 而一个 MailService 需要一个 IUserService,那么你就有了一个依赖循环.我看到了几个选项:

If a UserService needs an IMailService and a MailService needs an IUserService you have a dependency loop. I see a couple of options:

  1. 您的 UserService 是否立即需要 IMailService?当它需要发送消息时,你能传一个吗?

  1. Does your UserService need an IMailService right away? Could you pass one in when it needs to send a message?

是否可以按需查询解析器——也就是说,不要在构造函数中将 IUserService 传递给 MailService,而是在需要时编写 MailService 来解析 IUserService?

Can either query the resolver on-demand - that is, don't pass IUserService to MailService in the constructor but rather code MailService to resolve IUserService when it needs it?

这篇关于“检测到 Autofac 圆形组件依赖性"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆