Constructor Injection Performance

Mar 23, 2013 at 5:37 PM
This isn't a question about simpleInjector, but really just about the constructor injection 'pattern' (not sure if its really considered a pattern). I almost never see any discussions about performance when it comes to this specific part of DI. My concern is that the classes being passed in to a given constructor may not have a trivial overhead in constructing them, especially when you consider all of _it's_dpendencies that it may have. This is no problem if you end up using the class, but what if you don't? You could end up wasting an awful lot of cycles in this scenario when you multiply that across a large system. The stock answer is probably to say "refactor your class so it adheres to separation of concerns principles", and never has an unused dependency. But I don't buy that answer, it's too easy, and too academic. That's like saying you'll never have an if/then statement in a class, or only have one method on each class. I just don't think it's realistic, or even good design, to necessarily start designing my classes simply by what dependencies they have.

Or maybe there are other answers that I'm unaware of, I would very much like to hear other's thoughts on the matter.


Mar 23, 2013 at 5:57 PM
Here is an stackoverflow Q/A that talks about this. Bottom line is:
  • Creation of services should be very lightweight; you shouldn't do any initialization in them.
  • Overhead of your framework (WCF, Web Forms, etc) and your I/O is usually much bigger than creating deep object graphs with objects you never end up using.
Have you ever measured the performance of this? If you ensure that object creation if fast, you would hardly ever run into problems with this, especially with Simple Injector.

Besides, the alternatives to constructor injection are often worse. If you inject the Container instance directly into a type and query the container for instances (which is bad, bad practice) you'll find that performance is often lower, since you are calling into the container many times instead of just once per object graph. There are many other reasons not wanting to inject Container into a service btw. Just Google for "Service Locator anti-pattern".

If you however found out that performance is too slow in your case, post your details of your situation in a new thread. There are usually ways to improve performance for special scenarios.
Marked as answer by dot_NET_Junkie on 11/5/2013 at 7:38 AM