Dav*_*e L 4 coldfusion dependency-injection coldbox cfml wirebox
在这个例子中,我有一个叫做模型对象test.cfc具有相关性testService.cfc.
testWireBox testService通过属性声明注入.该对象如下所示:
component {
property name="testService" inject="testService";
/**
* Constructor
*/
function init() {
// do something in the test service
testService.doSomething();
return this;
}
}
Run Code Online (Sandbox Code Playgroud)
作为参考,testService有一个叫做doSomething()转储出一些文本的方法:
component
singleton
{
/**
* Constructor
*/
function init() {
return this;
}
/**
* Do Something
*/
function doSomething() {
writeDump( "something" );
}
}
Run Code Online (Sandbox Code Playgroud)
问题是,WireBox似乎testService在构造函数init()方法触发之后才会注入.所以,如果我在我的处理程序中运行它:
prc.test = wirebox.getInstance(
name = "test"
);
Run Code Online (Sandbox Code Playgroud)
我收到以下错误消息: Error building: test -> Variable TESTSERVICE is undefined.. DSL: , Path: models.test
只是为了理智,如果我修改,test以便testService在构造对象后引用,一切正常.这个问题似乎与构造函数方法隔离开来.
如何确保我的对象构造函数方法中可以引用我的依赖项?谢谢你的协助!
由于施工顺序,您不能在init()方法中使用属性或二次注入.相反,您可以在onDIComplete()方法中访问它们.我意识到WireBox文档只有一个传递引用,所以我添加了这个摘录:
https://wirebox.ortusbooks.com/usage/injection-dsl/id-model-empty-namespace#cfc-instantiation-order
CFC Building按此顺序进行.
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();
}
}
Run Code Online (Sandbox Code Playgroud)
注意,切换到构造函数注入也是可以接受的,但我个人的偏好是属性注入,因为需要接收参数的样板减少并在本地持久化.
https://wirebox.ortusbooks.com/usage/wirebox-injector/injection-idioms
| 归档时间: |
|
| 查看次数: |
152 次 |
| 最近记录: |