[英]Spring4D - How to resolve from container with TComponent parameter to auto factory
例如,我想解決一個 class 傳遞的 TComponent 和 TNotifyEvent,如下所示,但 TObject 的基本構造函數被調用,而不是 TMy。
GlobalContainer.RegisterType<TMy>;
GlobalContainer.RegisterFactory<Func<TComponent,TNotifyEvent,TMy>>(TParamResolution.ByType);
var F:=GlobalContainer.Resolve<Func<TComponent,TNotifyEvent,TMy>>;
F(Self,Self.OnActivate);
我可以通過如下編寫一些非常難看的代碼來解決這個問題,但我認為這種解決方案非常普遍,我一定是做錯了什么。
TOther = class
end;
TMy = class
public
constructor Create(C: TComponent; N: TNotifyEvent; O: TOther);
end;
procedure TForm2.Button1Click(Sender: TObject);
begin
GlobalContainer.RegisterType<TOther>;
GlobalContainer.RegisterType<TMy>;
GlobalContainer.RegisterType<Func<TComponent,TNotifyEvent,TMy>>(
function: Func<TComponent,TNotifyEvent,TMy>
begin
Result:=Func<TComponent,TNotifyEvent,TMy>(
function(O: TComponent; N: TNotifyEVent): TMy
begin
Result:=TMy.Create(O,N,GlobalContainer.Resolve<TOther>);
end
);
end
);
GlobalContainer.Build;
var F:=GlobalContainer.Resolve<Func<TComponent,TNotifyEvent,TMy>>;
F(Self,Self.OnActivate);
end;
constructor TMy.Create(C: TComponent; N: TNotifyEvent; O: TOther);
begin
OutputDebugString('Resolved');
end;
在此先感謝您的指點。
在開發中的最新提交之后,這現在應該可以工作了。
問題是類型化參數解析綁定到參數類型而不是參數類型。 在這種情況下,這會導致類型為 TForm2 的類型化值(取自傳遞的參數)與類型TForm2
的構造函數的TComponent
參數的類型不匹配,因為該匹配檢查類型標識而不是賦值兼容性。
修復后,類型參數解析完全適用於工廠 function 的參數類型,而不是可能(在對象的情況下)更窄的實際參數類型。
FWIW 以供將來參考 - 當手動注冊工廠時,通常不需要使用RegisterType
提供委托,但可以像這樣直接使用RegisterInstance
(請記住Spring.Func<...> has
const` 參數)當它沒有時任何捕獲的 state:
GlobalContainer.RegisterInstance<Func<TComponent,TNotifyEvent,TMy>>(
function(const O: TComponent; const N: TNotifyEVent): TMy
begin
// ....
end);
編輯:我還添加了自動檢測以獲得最佳參數分辨率默認值。 當工廠類型為Spring.Func<...>
時,它會自動使用ByType
,因此它可以從RegisterFactory
調用中省略。 對於所有其他類型,它像以前一樣默認使用ByName
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.