Reputation: 14736
I have read multiple articles about whether or not to do resource intensive operations in the constructor. Some of them say if it doesn't affect SRP or Testability then it is fine. I want an opinion on best practices for this scenario.
I am following the Composition Root principle mentioned here in my ASP.Net WebApi2 project and my controllers have got their dependent objects injected. Instead of injecting just a few dependencies, I want to inject the entire container and have any of the dependencies available. I have this class design where I am setting up the container property in the constructor. I dont know if this qualifies as bad practice.
public class AppContainer : IAppContainer
{
private readonly ContainerBuilder _builder ;
private IContainer _container ;
public AppContainer ()
{
_builder = new ContainerBuilder();
_builder.RegisterAssemblyModules(_assembly);
_container = _builder.Build();
}
public ContainerBuilder ContainerBuilder
{
get { return _builder; }
}
public IContainer Container
{
get { return _container;}
}
}
Is it bad design to call the .Build()
in the constructor as done above? I want to do this so that the AppContainer
's properties are initialized at the time of creation of the instance and not waiting for some method to be called for the properties to hold value.
Now in my controller instead of having something like this
public class HomeController : ApiController
{
private readonly IBusiness _bus;
public HomeController(IBusiness bus)
{
_bus = bus;
}
I can have something like this and expose the container directly. This way my controller's constructor definitions don't change everytime I needed a new dependency injected in.
public class HomeController : ApiController
{
private readonly IAppContainer _container;
public HomeController (IAppContainer container)
{
_container = container;
}
Upvotes: 0
Views: 1040
Reputation: 27861
Is it bad design to call the .Build() in the constructor as done above?
In general, it is not recommended that you do a lot in constructors.
Also, I don't recommend that you use the AppContainer
class at all. You are simply wrapping the container with the AppContainer
class and using it as a service locator which is an anti-pattern.
Your classes should declare their dependencies explicitly in the constructor as in your first example of HomeController
.
If you design your classes with the SOLID principles in mind, then your classes would be small and would not require a lot of dependencies so you almost wouldn't have to add new dependencies.
Please note that having too many dependencies (> ~3) might be an indication that you are violating the Single Responsibility Principle and is considered a code smell.
Upvotes: 1