1
votes

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. =)

1
Just register your type and it will by default resolve the constructor arguments for you. Since you're new to IoC, you might want to watch this super handy video: Deep Dive Into Dependency Injection And Writing Decoupled Quality and Testable Code - mason
Why don't you have two registrations? The first of IUserManager to UserManager and the second of IUnitOfWork to UnitOfWork. I personally don't use AutoFac but any container should resolve recursively so that when it resolves the UserManager it will automatically use UnitOfWork registration. - Wiktor Zychla

1 Answers

1
votes

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