问题描述
我是新来的IoC和我在我目前的项目中使用Autofac。
我有以下2类:
公共类UserService:IUserService
{
私人只读IUserRepository _repo;
私人只读IMailService _mailService;
公共UserService(IUserRepository回购,IMailService MailService的)
{
_repo =回购;
_mailService = MailService的;
}
}公共类MailService的:IMailService
{
私人只读IMailRepository _repo;
私人只读IUserService _userService;
公共MailService的(IMailRepository回购,IUserService userService)
{
_repo =回购;
_userService = userService;
}
}
起初,我UserService类并不需要MailService的类的实例,但现在它,它是因为引入到这一将UserService构造,这种循环依赖错误出现了,而且是一个新手,我不知道如何解决这个问题。
这是怎么我的班在Autofac目前注册的:
VAR建设者=新ContainerBuilder();//控制器
builder.RegisterControllers(Assembly.GetAssembly(typeof运算(UsersController)));//注册其他类
builder.RegisterType< UserRepository>()为<&IUserRepository GT;();
builder.RegisterType< MailRepository>()为<&IMailRepository GT;();
builder.RegisterType< UserService>()为<&IUserService GT;();
builder.RegisterType<&MailService的GT;()为<&IMailService GT;();
如果一个UserService需要一个IMailService和MailService的需要你有一个依赖循环的IUserService。我看到一对夫妇的选择:
-
请问您UserService需要IMailService,对吗?你可以传递之一时,它需要发送一个消息?
-
既可以查询点播解析器 - 也就是说,不通过IUserService到MailService的构造函数,而是code MailService的解决IUserService当它需要它
李? >
I am new to IoC and am using Autofac in my current project.
I have the following 2 classes:
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;
}
}
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.
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>();
If a UserService needs an IMailService and a MailService needs an IUserService you have a dependency loop. I see a couple of options:
Does your UserService need an IMailService right away? Could you pass one in when it needs to send a message?
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循环组件依赖检测到的”错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!