Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I heard a lot of people saying that it is a bad practice to use IoC.Resolve(), but I never heard a good reason why (if it's all about testing than you can just mock the container, and you're done).

now the advantages of using Resolve instead of Constructor Injection is that you don't need to create classes that have 5 parameters in the constructor, and whenever you are going to create a instance of that class you're not gonna need to provide it with anything

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
213 views
Welcome To Ask or Share your Answers For Others

1 Answer

IoC.Resolve<> is an example of the Service Locator pattern. That pattern imposes a few restrictions that constructor injection does not:

  • Objects can have no more fine-grained context than the application domain, due to the static calls
  • Objects decide which versions of dependencies to resolve. All instances of a certain class will get the same dependency configuration.
  • The temptation to couple code to the container is high, for example instead of creating an intention-revealing factory.
  • Unit testing requires container configuration, where the classes could just be created and used otherwise. (This is especially troublesome when you want to test multiple configurations of the same class, due to the second issue above.)
  • An application's structure cannot be inferred from its public API. (Constructor parameters are a good thing. They are not a problem you should feel the need to solve.)

These limitations, in my mind, relegate the Service Locator pattern to a middle ground between big-ball-of-mud and dependency injection: useful if you must use it, but by far not the best choice.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...