When field injection is used in Dependency Inversion Control containers, the fields are often not accessible at the time the constructor is called. The injection runs after the constructor, which is kind of annoying, because the fields may be required in the constructor’s body. Though it is not recommended to do any work in the constructor (it makes testing individual objects harder), sometimes, it is a nice feature to have.
Two parts are involved in this hack:
The first one is instantiating a typed object without calling the constructor. Most deserializers use the method FormatterServices.GetUnintializedObject(Type) to create just objects without calling the constructor.
The second one is calling an in-place constructor via reflection by using the ConstructorInfo.Invoke(object, object[]) overloaded method.
A small “Hello World” example explains the hack:
using System; using System.Runtime.Serialization; class Program { class FieldInjection { public string World; public FieldInjection() { Console.WriteLine("Hello " + World); } } static void Main(string[] args) { var instance = (FieldInjection) FormatterServices.GetUninitializedObject(typeof (FieldInjection)); instance.World = "World"; instance.GetType().GetConstructor(new Type[0]).Invoke(instance, null); } }
Alternatively, fields could be injected via reflection, which would be an option for future Dependency Injection Containers.