在这个例子中,我有一个名为test.cfc
的模型对象,它有一个依赖项testService.cfc
。
test
让WireBox通过属性声明注入testService
。对象看起来像这样:
component {
property name="testService" inject="testService";
/**
* Constructor
*/
function init() {
// do something in the test service
testService.doSomething();
return this;
}
}
作为参考,testService
有一个名为doSomething()
的方法,它会转储一些文本:
component
singleton
{
/**
* Constructor
*/
function init() {
return this;
}
/**
* Do Something
*/
function doSomething() {
writeDump( "something" );
}
}
问题是,WireBox似乎直到构造函数init()
方法激发之后才注入testService
。所以,如果我在我的处理程序中运行这个:
prc.test = wirebox.getInstance(
name = "test"
);
我收到以下错误消息:Error building: test -> Variable TESTSERVICE is undefined.. DSL: , Path: models.test
为了保持理智,如果我修改test
,以便在构建对象后引用testService
,那么一切都会正常工作。这个问题似乎与构造函数方法无关。
如何确保我的依赖项可以在我的对象构造函数方法中被引用?感谢您的帮助!
由于构造顺序的原因,不能在init()
方法中使用属性或setter注入。相反,您可以在onDIComplete()
方法中访问它们。我意识到WireBox文档对此只有一个间接的参考,所以我添加了以下摘录:
https://wirebox.ortusbooks.com/usage/injection-dsl/id-model-empty-namespace#cfc-实例化订单
CFC建筑按此顺序发生。
- 组件用
createObject()
实例化 - CF自动运行伪构造函数(方法声明之外的任何代码(
- 调用
init()
方法(如果存在(,传递任何构造函数参数 - 属性(mixin(和设置注入发生
- 调用
onDIComplete()
方法(如果存在(
因此,您的CFC的正确版本如下:
component {
property name="testService" inject="testService";
/**
* Constructor
*/
function init() {
return this;
}
/**
* Called after property and setter injections are processed
*/
function onDIComplete() {
// do something in the test service
testService.doSomething();
}
}
注意,切换到构造函数注入也是可以接受的,但我个人更喜欢属性注入,因为需要接收参数并在本地保持它的样板文件减少了。
https://wirebox.ortusbooks.com/usage/wirebox-injector/injection-idioms