I am using Spring4d framework for dependency injection and other things.
In the application entry point, I have to create the application "Main" form. Though, I do not know of any other way than
Application.CreateForm(TMainForm, MainForm)
to create this.
Is it possible to create the Main form using Spring4d dependency injection ? Like so :
MainForm := GlobalContainer.Resolve<IMainForm>;
and then set it to be the form that will be shown when I open the application?
When you register your main form with the DI container you can specify the factory function to create the instance by passing it to the DelegateTo
method.
In my opinion there is no need to resolve the main form as interface because it is the composition root and it will not be passed anywhere else so I will register it like following.
container.RegisterType<TMainForm,TMainForm>.DelegateTo(
function: TMainForm
begin
Application.CreateForm(TMainForm, Result);
end);
And then you can just resolve it calling
container.Resolve<TMainForm>;
However the benefit of letting the container resolve the form is that it may inject dependencies into it which will not happen here since the code inside of CreateForm
creates the instance. That is where the possibility to call additional methods via container after construction comes into play. So instead of passing dependency into the constructor as usual you can add a lets say Init
method to the form class that takes the dependencies it needs and add the [Inject]
attribute to it. That will tell the container to call this method after the instance was created (in our case through the factory function passed to the DelegateTo method) and pass all required dependencies to it.
A minimal empty main form that can take dependencies via container would look like this:
TMainForm = class(TForm)
public
[Inject]
procedure Init(...);
end;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With