I have an situation here that looks very like a “SELECT N+1” from the NHibernate world.
I’m creating an application ASP.NET MVC app and the HomeController needs an IUserSignUpService. The IUserSignUpService “lives” in the Application Service Layer where it is binded to the concrete class UserSignUpService.
The UserSignUpService has 2 dependencies:
public IUserRepository UserRepository { get; set; }
public Domain.Services.IUserSignUpService SignUpService { get; set; }
public UserSignUpService(IUserRepository userRepository, Domain.Services.IUserSignUpService signUpService)
{
this.UserRepository = userRepository;
this.SignUpService = signUpService;
}
When Autofac is resolving the IUserSignUpService that lives in the Application Service Layer, it needs to resolve the IUserRepository dependency that lives in the Persistence Layer and a Domain.Services.IUserSignUpService (I know, same name, but they are different) that lives inside the Domain and performs several actions before execute the INSERT SQL to the database.
The IUserRepository interface is implemented by the UserRepository class that needs an ISession instance to be injected via constructor.
My point here is:
If I keep using this approach, every time I receive a HttpRequest to the HomeController I’m going to start a new ISession (because it is a constructor dependency of UserRepository, which is a constructor dependency to IUserSignUpController which is a constructor dependency of HomeController).
I don’t need everything every time. Maybe I could instruct Autofac to only resolve the ISession when there’s an instance of the IUnitOfWork interface in the current LifeTimeScope.
Is it possible?
Test whether doing extra work to not construct an ISession is premature optimization. Is there a significant perf hit?
If so, you could wrap whatever constructor dependency that you “don’t need every time” in a Lazy<> and Autofac will delay instantiation.