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>();
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…