5

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

John B
  • 20,062
  • 35
  • 120
  • 170
  • 2
    As always, profile first. However, I'm going to guess that resolving the dependencies is orders of magnitude slower than instantiating them. – Bryan Boettcher Mar 13 '12 at 20:22
  • @insta Wow, I didn't see the forest through the trees. But do Ninject and/or other IoC containers cache dependency resolving? – John B Mar 13 '12 at 20:23
  • 1
    I added an answer below that should help you ... I've run into this exact same problem before. Most people (myself included) don't know that you can override the controller factory ASP.NET MVC uses to create controllers. A custom one can integrate your IoC container tightly and spool up dependencies as they're needed. – Bryan Boettcher Mar 13 '12 at 20:33
  • @insta I figured there was a way to hook in on a "lower level". Thanks! – John B Mar 13 '12 at 20:35
  • 1
    10 dependencies per class? Please read this question: stackoverflow.com/questions/9686567/dependency-injection-what-to-do-when-you-have-a-lot-of-dependencies, and this question: http://stackoverflow.com/questions/2420193/dependency-injection-constructor-madness. – Steven Mar 13 '12 at 20:36
  • 2
    It doesn't matter: http://blog.ploeh.dk/2011/03/04/ComposeObjectGraphsWithConfidence.aspx – Mark Seemann Mar 14 '12 at 04:47

2 Answers2

7

every request will instantiate every single service that my application uses, whether or not the specific controller uses all of them.

I believe you've answered your question yourself, this is not a good approach. Moreover using such kind of dependency resolving (Service Locator injection) is a bad practice since Controller's API becomes messy. Controller clients are not aware of which services really necessary for a specific controller so you might end up with unexpected run time errors, unit testing will be a mess as well.

BTW one more suggestion - mark all classes which are considered to be a base class by abstract keyword, in this way you can avoid using it as a concrete class. Designing and implementing a base class is a concrete design decision, so make your design intentions clear.

Regarding a cost of instantiation, in your case it would not make a big difference, but in general to reduce a cost of heavy objects instantiation you can:

  • Use Prototype pattern to "avoid the inherent cost of creating a new object in the standard way (e.g., using the 'new' keyword) when it is prohibitively expensive for a given application" (c) Wikipedia
  • Use Lazy Initialization for services which are not needed from the start of the owner object life time, so those would be initialized on demand. Since .NET Framework 4.0 yo can use built in Lazy(T) class
sll
  • 61,540
  • 22
  • 104
  • 156
  • Good answer, but I'd like to defend myself a little. My controller API is now VERY clean because I abstracted all the dependencies into the service locator. I could do a more specific interface for each controller, but for my particular application/load, it's overkill. Also, I wont suffer from runtime errors, because my unit tests ensure the code runs, and runs correctly. But I do see your point about the lack of awareness of dependencies. Now that I've done this, I have no easy way of knowing a Controller's dependencies (for my own reference). I'm OK with that, for now. – John B Mar 14 '12 at 13:30
2

I think the solution you're looking for here is to use a custom controller factory. That way, each controller created has exactly the dependencies it needs. Here's one for StructureMap, from weblogs.asp.net:

using StructureMap; 
public class StructureMapControllerFactory : DefaultControllerFactory { 

    protected override IController GetControllerInstance(Type controllerType) {
        try {
           return ObjectFactory.GetInstance(controllerType) as Controller;
        }
        catch (StructureMapException) {
            System.Diagnostics.Debug.WriteLine(ObjectFactory.WhatDoIHave());
            throw;
        }
    }
}

protected void Application_Start() {
    RegisterRoutes(RouteTable.Routes);

    //Configure StructureMapConfiguration
    // TODO: config structuremap        

    //Set current Controller factory as StructureMapControllerFactory
    ControllerBuilder.Current.SetControllerFactory(new StructureMapControllerFactory()); 
}
Bryan Boettcher
  • 4,412
  • 1
  • 28
  • 49
  • Thanks for the reply, but I think I already have this? Previously I had controller's constructors setup to accept interfaces for their service dependencies. Ninject and it's Bootstrapper to accomplish this. – John B Mar 14 '12 at 13:32
  • Then what's the point of a base controller that takes every dependency? If your controllers have been pruned to take just the constructor arguments they need, however they're populated, then that's the best you can do. – Bryan Boettcher Mar 14 '12 at 14:14
  • So instead of having 10 private fields, 10 constructor arguments, and 10 assignments in the constructor body, I handle it once in the BaseController. That way when I add a new dependency, the Controller constructors wont change. Instead, the BaseController will get a new field and assignment in it's constructor. Similarly, this simplifies my test setup as well. I have a BaseTests class that sets up fields for each mock, in one place. – John B Mar 14 '12 at 14:36