在Spring4D中如何为相同接口注册多个自动工厂。

huangapple go评论56阅读模式
英文:

In Spring4D how to register multiple auto factories for same interface

问题

我想通过容器为以下类提供构造函数参数,但无法找到注册多个自动工厂的方法。

TItemFactory = class(TInterfacedObject, IItemFactory)
private
  fFactories: TArray<Func<IHost, IItem>>;
protected
  function CreateInstance(Host: IHost): TArray<IItem>;
public
  constructor Create(Factories: TArray<Func<IHost, IItem>>);
end;

如果我想要多种类型的项目,我可以将它们注册为

GlobalContainer.RegisterType<IItem, TItem1>('Item1');
GlobalContainer.RegisterType<IItem, TItem2>('Item2');

如果我只有一种类型的项目,我可以轻松地

GlobalContainer.RegisterType<IItem, TItem1>;
GlobalContainer.RegisterFactory<Func<IHost, IItem>>;

但我可以看到给多个自动工厂命名没有意义,因为它们只引用 IItem 而不是 TItem1 或 TItem2。

英文:

I want to provide the constructor arguments to the following class via the container but am unable to find a way of registering the multiple auto factories.

TItemFactory = class(TInterfacedObject, IItemFactory)
private
  fFactories: TArray&lt;Func&lt;IHost,IItem&gt;&gt;;
protected
  function CreateInstance(Host: IHost): TArray&lt;IItem&gt;;
public
  constructor Create(Factories: TArray&lt;Func&lt;IHost,IItem&gt;&gt;);
end;

If I wanted to have multiple types of items I could register them as

GlobalContainer.RegisterType&lt;IItem,TItem1&gt;(&#39;Item1&#39;);
GlobalContainer.RegisterType&lt;IItem,TItem2&gt;(&#39;Item2&#39;);

If I only had one type of item I could easily

GlobalContainer.RegisterType&lt;IItem,TItem1&gt;;
GlobalContainer.RegisterFactory&lt;Func&lt;IHost,IItem&gt;&gt;;

But I can see there is no point in naming multiple auto factories as they only reference IItem and not TItem1 or TItem2.

答案1

得分: 0

"RegisterFactory"的参数中有两个重载,您可以在其中指定"resolvedServiceName"。

GlobalContainer.RegisterFactory&lt;Func&lt;IHost, IItem&gt;&gt;('ItemFactory1', 'Item1');
GlobalContainer.RegisterFactory&lt;Func&lt;IHost, IItem&gt;&gt;('ItemFactory2', 'Item2');
英文:

Simple, look at the parameters of RegisterFactory, there are two overloads where you can specify the resolvedServiceName.

GlobalContainer.RegisterFactory&lt;Func&lt;IHost, IItem&gt;&gt;(&#39;ItemFactory1&#39;, &#39;Item1&#39;);
GlobalContainer.RegisterFactory&lt;Func&lt;IHost, IItem&gt;&gt;(&#39;ItemFactory2&#39;, &#39;Item2&#39;);

huangapple
  • 本文由 发表于 2023年5月10日 21:50:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76219244.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定