在本例中,我有一个名为 test.cfc
的模型对象。有一个依赖 testService.cfc
.test
有 WireBox 注入(inject) testService
通过属性(property)声明。该对象如下所示:
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 似乎没有注入(inject)
testService
直到构造函数 init()
之后方法触发。所以,如果我在我的处理程序中运行它:prc.test = wirebox.getInstance(
name = "test"
);
我收到以下错误消息:
Error building: test -> Variable TESTSERVICE is undefined.. DSL: , Path: models.test
只是为了理智,如果我修改
test
这样testService
在构造对象后被引用,一切正常。该问题似乎与构造函数方法无关。如何确保我的依赖项可以在我的对象构造函数方法中被引用?感谢你的协助!
最佳答案
由于构造顺序,您不能在 init()
中使用属性或 setter 注入(inject)。方法。相反,您可以在 onDIComplete()
中访问它们。方法。我意识到 WireBox 文档只有一个对此的传递引用,所以我添加了以下摘录:
https://wirebox.ortusbooks.com/usage/injection-dsl/id-model-empty-namespace#cfc-instantiation-order
CFC build 按此顺序进行。
createObject()
实例化组件init()
调用方法(如果存在),传递任何构造函数参数 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();
}
}
请注意,切换到构造函数注入(inject)也是可以接受的,但我个人的偏好是属性注入(inject),因为减少了需要接收参数并在本地持久化的样板。
https://wirebox.ortusbooks.com/usage/wirebox-injector/injection-idioms
关于dependency-injection - 如何使 WireBox 注入(inject)的依赖项可用于构造函数方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53214393/