I searched my brains out and wasn’t able to find a suitable answer, so here we go! I have the following property in each of my forms or objects:
private RootWorkItem m_RootWorkItem;
[RootWorkItem(Inject = true)]
public RootWorkItem RootWorkItem {
get {
if (m_RootWorkItem == null) {
m_RootWorkItem = new RootWorkItem();
}
return m_RootWorkItem;
}
}
Note that RootWorkItem is a class I have designed that contains a collection of Services (Collection). Basically, all my services are loaded from external DLL files using reflection and Activator.CreateInstance, and put into RootWorkItem.Services.
But how on earth can I actually “inject” the very first RootWorkItem created into every other RootWorkItem marked with my attribute in my program?
How do these DI patterns ACTUALLY “DO” the injection “into” a property? I know the concepts of DI but I am trying to write my own, extremely basic DI for only one single object. I’ve been messing with reflection tons to try and find some suitable way to do this and I’m not even closed to coming up with a right way to do it.
Edited for more clearer question:
How does a DI framework/service know when an object is created that contains the property to inject?
ie:
class MyForm : Form {
[RootWorkItem(Inject = true)]
public RootWorkItem RootWorkItem { get; set; }
end class
class Program {
Main {
MyForm form = new MyForm();
form.Show();
}
end class
How does it know to inject the property value when the form is created, if nothing notifies the service that it was created or it needs injected?
You’re asking the right question: “How does it know to inject the property value when the form is created, if nothing notifies the service that it was created or it needs injected?”
You’re also correct when you say “if nothing notifies the service that it was created or it needs injected”, then the DI framework cannot do its job.
However, the DI framework does know, because you use the DI framework to create the object that is having its dependencies injected. In this case, you use the DI framework to create your form, so it is aware of the object and can inject dependencies.
Instead of
Do
Now, your DI framework knows about the object!
Essentially,
newis the enemy of DI, since it means the caller is controlling construction of the object. Instead, the caller is meant to leave that responsibility to someone else, ie, the DI framework. The caller should only ever ask the DI framework to provide/construct/configure objects.