在本例中,我有一个名为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,那么一切都会正常工作。这个问题似乎与构造函数方法隔离开来。
如何确保在对象构造函数方法中引用我的依赖项?谢谢你的帮助!
发布于 2018-11-08 19:39:16
由于构造的顺序,您不能在init()方法中使用属性或setter注入。相反,您可以在onDIComplete()方法中访问它们。我意识到WireBox文档对此只有一个偶然的引用,因此我添加了以下摘录:
https://wirebox.ortusbooks.com/usage/injection-dsl/id-model-empty-namespace#cfc-instantiation-order
CFC大楼按此顺序进行。
createObject()实例化。init()方法(如果存在的话),传递任何构造函数argsonDIComplete()方法(如果存在的话)因此,您的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
https://stackoverflow.com/questions/53214393
复制相似问题