完成实现:使用接口进行依赖注入的容器

问题描述 投票:0回答:1

我希望完成此实施。

这是一个非常简单的容器模型,用于使用 Delphi 中的接口进行依赖注入。

我在 YouTube 上观看了一堂课,其中介绍了方法,但只有它们的签名,没有介绍如何实现。

我设法编写了几乎所有这些,我认为它们会起作用,除了主要函数之一:“function Get:I;”

unit uContainerDefault;

interface

uses
  System.TypInfo,
  System.SysUtils,
  System.Generics.Collections;

type
  TGetter = TFunc<IInterface>;

  TContainer = class
  strict private
    FRecords: TDictionary<PTypeInfo, TGetter>;

    class var FDefault: TContainer;
    class function GetDefault: TContainer; static;

  public
    class constructor Create;
    class destructor Destroy;

    constructor Create;
    destructor Destroy; override;

    procedure Register<I: IInterface>(const pGetter: TGetter);

    function Get<I: IInterface>: I;

    class property Default: TContainer read GetDefault;
  end;

implementation

{ TContainer }

class constructor TContainer.Create;
begin
  FDefault := TContainer.Create;
end;

constructor TContainer.Create;
begin
  FRecords := TDictionary<PTypeInfo, TGetter>.Create;
end;

destructor TContainer.Destroy;
begin
  FRecords.Free;
  inherited;
end;

class destructor TContainer.Destroy;
begin
  FDefault.Free;
end;

function TContainer.Get<I>: I;
begin
  {With this code, can I get from the dictionary what "TFunc<IInterface>" is that will result in the interface,
  but I don't know if I should use it to form the result.}
  FRecords.Items[TypeInfo(I)];
end;

class function TContainer.GetDefault: TContainer;
begin
  Result := FDefault;
end;

procedure TContainer.Register<I>(const pGetter: TGetter);
begin
  FRecords.Add(TypeInfo(I), pGetter);
end;

end.

初始化类“TProduct”时如何调用 Register 方法的示例:

initialization
  TContainer.Default.Register<IProduct>(
    function: IInterface
    begin
      Result := TProduct.Create;
    end);

如何在与“Product”实体一起使用的表单上调用 Get 方法的示例:

begin
  TContainer.Default.Get<IProduct>.GetProduct;
end;
function TContainer.Get<I>: I;
begin
  {With this code, can I get from the dictionary what "TFunc<IInterface>" is that will result in the interface,
  but I don't know if I should use it to form the result.}
  FRecords.Items[TypeInfo(I)];
end;
delphi dependency-injection interface containers
1个回答
0
投票

经过一番努力,我做到了! 效果很好。

看看结果如何:

... 函数 TContainer.Get: I; 开始 支持(FRecords.Items[TypeInfo(I)], PTypeInfo(TypeInfo(I)).TypeData.GUID, Result); 结尾; ...

有人想添加一些东西吗? 谢谢

© www.soinside.com 2019 - 2024. All rights reserved.