I personally see this as a benefit. For example, I write this code all the time:
public class MyService : IService { // Boilerplate! private readonly IDependency1 dep1; private readonly IDependency2 dep2; private readonly IDependency3 dep3; public MyService(IDependency1 dep1, IDependency2 dep2, IDependency3 dep3) { // More boilerplate! this.dep1 = dep1; this.dep2 = dep2; this.dep3 = dep3; } // Finally something useful void IService.DoOperation() { using (var context = this.dep1.CreateContext()) { this.dep2.Execute(context); context.Commit(); } this.dep3.Log("Success"); } }
It would be nice to write this as follows:
public class MyService : IService { public MyService(private IDependency1 dep1, private IDependency2 dep2, private IDependency3 dep3) { } void IService.DoOperation() { using (var context = this.dep1.CreateContext()) { this.dep2.Execute(context); context.Commit(); } this.dep3.Log("Success"); } }
I'm sorry that I can’t just leave all the plumbing with the declaration of the dependency fields and assigning them in my constructor.
UPDATE
Our prayers may have been answered. The C # team can add “concise syntax for class definitions,” such as properties that “can be declared directly from the constructor” in C # 6.0. Let hope such a feature makes light.
So your main question is: “Why don't languages integrate Injection Dependency into the kernel?” They do. Scala and F # make this a lot easier, and C # hopefully follows.
In the meantime, I tried to overcome this obstacle by writing a T4 template that generates a constructor for you in a partial class, but after working with it for several weeks in the application, it really did not work as expected.
Steven
source share