dependency-injection - 如何使 WireBox 注入(inject)的依赖项可用于构造函数方法?

标签 dependency-injection coldfusion cfml coldbox

在本例中,我有一个名为 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() 实例化组件
  • CF 自动运行伪构造函数(a 方法声明之外的任何代码)
  • init()调用方法(如果存在),传递任何构造函数参数
  • 发生属性(mixin)和设置注入(inject)
  • 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/

    相关文章:

    coldfusion - cfscript 中的转储函数在哪里?

    image-processing - 如何使用 ColdFusion 缩放图像而不损失分辨率?

    tomcat - ColdFusion 页面显示为原始代码

    regex - 使用正则表达式删除 RTF 模板中占位符的父段落

    dependency-injection - Ninject Conditional Self 绑定(bind)以更改范围(对于任务调度程序)无法正常工作?

    java - 如何从不同的范围创建对象

    java - 为什么 Spring @Configuration 类继承没有按预期工作?

    asp.net-core - 是否对在整个 ASP.NET Core 3 应用程序中使用完全相同的 HTTPContextAccessor 实例感到困惑?

    coldfusion - Coldfusion 的 createObject() 函数如何搜索组件?

    coldfusion - 如何在 cfscript 标记内执行 cfdump?