After studing the Autofac documentation , and some stackoverflow questions
Best Practices for IOC Container ,
IoC Container. Inject container
I understand that I need put container on highes level,and after that pass it thrue needed classes.
f.ex I have high level class controller
public class AccountController : Controller
{
private readonly IUserManager userManager;
public AccountController(IUserManager userManager) //I configure Global.asax and there will
{ //be UserManager class. OK.
this.userManager = userManager;
}
}
on lower level I have UserManager class whit parameter IUnitOfWork. Should I put there new UnitOfWork instance or do it with some container?
public class UserManager : IUserManager
{
readonly IUnitOfWork _unitOfWork;
public UserManager (IUnitOfWork unitOfWork)
{
this._unitOfWork = unitOfWork;
}
}
Piece of autofac configuration.
conteinerBuilder.RegisterType<UserManager>().As<IUserManager>()
.WithParameter("unitOfWork",new UnitOfWork()) //This is what bothers me
//Like I understand we wanna
//work with abstraction not with some
//implementations but there I must use
//UnitOfWork
Tell me which way to dig, I'm completely confused. I'll be greateful for any help. =)
When using IOC container you have to register all your services in the container. When a service is requested, this is the responsibility of the container to create the graph of needed services.
You can register both services like this :
builder.RegisterType<UserManager>().As<IUserManager>();
builder.RegisterType<UnitOfWork>().As<IUnitOfWork>();
The WithParameter
method is usefull for some requirement, for example when you need some parameters from configuration to create an instance :
builder.RegisterType<XService>()
.As<Service>()
.WithParameter("key1", config.GetValue("key1"));
See Passing parameters to Register from the autofac documentation for more information
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.