With Spring4d, you can register custom factories like so
aContainer.RegisterInstance<TFunc<string, TMyObject>>(function(aName : string):TMyObject
begin
Result := TMyObject.Create(aName);
end);
In this manner, I would beleive that for every dependency that inherits from TComponent
, one who wants to pass the owner would either do
// Registrations
aContainer.RegisterInstance<TFunc<TComponent, TMyObject>>(function(Owner : TComponent):TMyObject
begin
Result := TMyObject.Create(Owner);
end);
// Then in code
constructor TMyClass.Create(aFctry : TFunc<TComponent, TMyObject>);
begin
fObj := aFctry(Self);
end;
Or one could also do
aContainer.RegisterType<TMyObject, TMyObject>;
// In code
constructor TMyClass.Create(aObj : TMyObject);
begin
fObj := aObj;
InsertComponent(aObj);
end;
Though, this is error prone / adds code just to pass in the owner. Is there a built-in way of getting a factory that takes a TComponent as parameter without having to register it in the container beforehand ?
Because often I will use
constructor MyObject.Create(aDep : TFunc<TMyDep>);
Without registering the TFunc<TMyDep>
dependency, but only the TMyDep
type.
It it possible to pass something like
constructor MyObject.Create(aDep : TFunc<TComponent, TMyDep>);
Without having to register it in the container ?