我是IoC的新手,并且在当前项目中使用Autofac。
我有以下2个类(class):
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构造函数以来,就已经出现了这种循环依赖性错误,并且作为一个新手,我不确定如何解决这个问题。
这是我的类(class)目前在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,则您将具有依赖项循环。我看到几个选择: