Is the DI pattern limiting wrt expensive object creation coupled with infrequent dependency usage?

前端 未结 4 1958
甜味超标
甜味超标 2020-12-16 04:19

I\'m having a hard time getting my head around what seems like an obvious pattern problem/limitation when it comes to typical constructor dependency injection. For example

相关标签:
4条回答
  • 2020-12-16 04:45

    No you are not tied to the limitations you have listed. As of .net 4 you do have Lazy(Of T) at your disposal, which will allow you to defer instantiation of your dependencies until required.

    It is not assumed that object construction is dirt-cheap and consequently some DI containers support Lazy(Of T) out of the box. Whilst Unity 2.0 supports lazy initialization out of the box through automatic factories, there is a good article here on an extension supporting Lazy(Of T) the author has on MSDN.

    0 讨论(0)
  • 2020-12-16 04:47

    Isn't your controller a singleton though? That is the normal way to do it in Java. There is only one instance created. Also you could split the controller into multiple controllers if the roles of the actions is so distinct.

    0 讨论(0)
  • 2020-12-16 04:51

    If you have a lot of fields that aren't being used by every member this means that the class' cohesion is low. This is a general programming concept - Constructor Injection just makes it more visible. It's usually a pretty good indicator that the Single Responsibility Principle is being violated.

    If that's the case then refactor (e.g. to Facade Services).

    You don't have to worry about performance when creating object graphs.

    When it comes to side effects, (DI) constructors should be simple and not have side effects.

    0 讨论(0)
  • 2020-12-16 04:51

    Generally speaking, there should be no major costs or side effects of object construction. This is a general statement that I believe applies to most (not all) objects, but is especially true for services that you would inject via DI. In other words, constructing a service class automatically makes a database/service call, or changes the state of your system in a way that would have side effects is (at least) a code smell.

    Regarding instances that go unused: it's hard to create a system that has perfect utilization of instances within dependent classes, regardless of whether you use DI or not. I'm not sure achieving this is very important, as long as you are adhering to the Single Responsibility Principle. If you find that your class has too many services injected, or that utilization is really uneven, it might be a sign that your class is doing too much and needs to be split into two or more smaller classes with more focused responsibilities.

    0 讨论(0)
提交回复
热议问题