1

From Using the Simple Injector in Simple Injector documentation:

Note: Calling the GetInstance method in the constructor is suboptimal and should be avoided whenever possible. With ASP.NET Web Forms however, it is hard to completely avoid this. Please see the Integration Guide for alternatives.

Why exactly is it suboptimal?

I did notice that this kind of usage can cause issues due to the intentional limitation that the container is locked after the first call to resolve. Thus if you register A, then create a collection of ISomething - one of which has a dependency on A - and then you register that collection using RegisterAll(), then you run into trouble because one of the ISomethings resolves A, preventing the subsequent registration of the collection.

However I imagine there is more to "suboptimal" than this.

Steven
  • 166,672
  • 24
  • 332
  • 435
Gigi
  • 28,163
  • 29
  • 106
  • 188

1 Answers1

2

Calling back into the container from within the constructor of your type is sub optional, because:

  • You render your DI library blind, and disallow it to see which dependencies a type has, which makes it impossible to warn you about any misconfigurations you might have made.
  • Makes it impossible for the DI library to optimize the object graph construction for you.
  • Makes it impossible to apply features such as Context Based Injection that work by changing the expression tree before it gets compiled to code.
  • You make it harder to unit test code that calls into the container.

Calling back into the container is an anti-pattern called Service Locator.

Unfortunately, the documentation you are pointing at is a bit outdated and in general we advice against using this type of construct. The ASP.NET Web Forms Integration page therefore describes a better solution for this using explicit property injection.

Steven
  • 166,672
  • 24
  • 332
  • 435
  • Whether Service Locator is an anti-pattern is arguable - see [this answer](http://stackoverflow.com/a/22795888/983064). – Gigi Aug 14 '14 at 09:54
  • 1
    @Gigi: For any 'normal' line-of-business development (so anything that is not a reusable library) Service Locator has so many downsides that there's not much arguing about that. The argument that Jgauffin makes in is answer is invalid, because that's not an example of Service Lcoation. I added a comment to his answer about that. – Steven Aug 14 '14 at 10:04