C# – Why Modifier Access for Properties Needs to Be Public in Unity

cdependency-injection

Why does the modifier access for the properties need to be public with Unity?

I'm very interested in a detailed explanation for my question. I read about tips to do it in other ways, but not a detailed explanation about why this can't be declared explicitly in my code.

Best Answer

Why would you need to inject private properties? That's not what DI is for. Injecting private properties would violate encapsulation.

One of the constructor overloads on your class should specify everything the class needs to instantiate. If the class can't specify what it needs in it's public API, then it doesn't need it.

From http://natpryce.com/articles/000783.html (emphasis mine):

There are two aspects to Dependency Injection. Firstly, an object's interface should define the services that the object requires as well as those it provides. Secondly, the code that satisfies the requirements of an object by giving it a reference to the services of is collaborators is external to both the object and its collaborators. For this reason, the pattern also used to be called "third-party binding" or "third-party connect": some third party is responsible for connecting and satisfying the service requirements of a component (the party of the first part) with those provided by another component (the party of the second part).

The name "Dependency Injection" only relates to the second aspect. And worse, makes it sound like dependencies are "injected" through the object's encapsulation boundary rather than explicitly defined as part of the object's API. And so we get "dependency injection" APIs, like that in JavaEE 5, which use reflection to poke dependencies into an object's private fields, bypassing the constructor, adding a great deal of complexity to client & test code while not providing the benefits that the Dependency Injection pattern should deliver.