In general does the instantiation of classes with methods, but no fields or properties, have much overhead?
I'm developing an ASP.NET MVC application that heavily uses constructor injection and some controllers have up to 10 dependencies so far. But due to the high number of dependencies, I resorted to a IMyAppServiceProvider
interface and class that provides generic access to all the dependencies, through the DependencyResolver in MVC 3.
I ripped out all my application specific code and created a Gist with my basic setup (This doesn't include the BaseController setup mentioned below though).
I also created a BaseController class that accepts the IMyAppServiceProvider
. All controllers inherit from this base class. The base class takes the IMyAppServiceProvider
object and has protected variables for all of the various services. Code looks something like this:
public class BaseController
{
protected IService1 _service1;
protected IService2 _service2;
protected IService3 _service3;
// ...
public BaseController(IMyAppServiceProvider serviceProvider)
{
_service1 = serviceProvider.GetService<IService1>;
_service2 = serviceProvider.GetService<IService2>;
_service3 = serviceProvider.GetService<IService3>;
// ...
}
}
This makes the code for the controllers "squeaky clean". No private/protected variables, no assignments in the constructor, and the services are referenced by the base class protected variables. However, every request will instantiate every single service that my application uses, whether or not the specific controller uses all of them.
My services are simple and just contain method calls with some business logic and database interaction. They are stateless and have no class fields or properties. Therefore, instantiation should be fast, but I'm wondering if this is a best practice (I know that's a loaded term).