delphi - 如何将参数从实例化程序传递给spring4d依赖注入框架中的构造函数? [英] delphi - how to pass a parameter from the instantiator to a constructor in the spring4d dependency injection framework?
问题描述
可以从创建点注册一个预期要传递的参数的类?
It's possible to register a class with a parameter expected to be passed from the point of creation?
我知道可以这样做:
GlobalContainer.RegisterType<TUserProcessor>.Implements<IUserUpgrader>.
AsTransient.DelegateTo(
function: TUserProcessor
begin
Result := TUserProcessor.Create(GetCurrentUser);
end
);
但是,这些参数绑定到容器注册的执行上下文,而不是对象获取的位置
But there the parameters are binded to the execution context where the container gets registered and not where the object get's intantiated.
可以这样吗?
GlobalContainer.Resolve<IMathService>([FCurrentUser]);
我知道一些peoble倡导者拥有非常简单的构造函数,但有时候构造函数参数看起来很清楚要执行的方法:
I know some peoble advocate to have very simple constructors, but there are times when a constructor parameter looks clearly the way to go:
-
构造的对象需要object参数才能正常工作,因此必须满足引用。参数也使该约束更加明显地看着类。
The object constructed needs the object parameter to work, so the reference must be satisfied. The parameter also makes that constraint much more obvious looking at the class.
您可以在方法或属性中分配引用,并在其他方法中引发和异常如果您尝试使用该对象而不首先进行分配。我不喜欢编写这种类型的代码,这只是浪费时间,只需使用构造函数参数并检查。较少的代码,更好的IMO。
You can assign the reference in a method or property and raise and exception in every other method if you try to use the object without first making the assignment.. I don't like writing this type of code it's simply a waste of time, just use the constructor parameter and check there. Less code, the better IMO.
另外,正在传递的对象是使用容器构建新对象的对象(例如Transaction对象)并且有一些状态(这不是我可以用容器获得的新对象)。
Also the object being passed it's local to the object that constructs the new object using the container (for example a Transaction object) and has some state (it's not a new object that I can get with the container).
推荐答案
我已经在Unity中添加了解析器覆盖。
I have added resolver overrides as in Unity.
所以你可以写:
program Demo;
{$APPTYPE CONSOLE}
uses
Classes,
Spring.Container,
Spring.Container.Resolvers;
type
IUserUpgrader = interface
['{ADC36759-6E40-417D-B6F7-5DCADF8B9C07}']
end;
TUser = class(TObject);
TUserProcessor = class(TInterfacedObject, IUserUpgrader)
public
constructor Create(AUser: TUser);
end;
constructor TUserProcessor.Create(AUser: TUser);
begin
Writeln('called constructor with passed user');
end;
begin
GlobalContainer.RegisterType<TUserProcessor>.Implements<IUserUpgrader>;
GlobalContainer.Build;
GlobalContainer.Resolve<IUserUpgrader>(
TOrderedParametersOverride.Create([TUser.Create]));
GlobalContainer.Resolve<IUserUpgrader>(
TParameterOverride.Create('AUser', TUser.Create));
Readln;
end.
这篇关于delphi - 如何将参数从实例化程序传递给spring4d依赖注入框架中的构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!