为什么依赖注入在我的CF工厂对象中失败?

时间:2009-07-19 18:01:34

标签: coldfusion dependency-injection

我收到此错误

  

元素INSTANCE在VARIABLES中未定义。

我没有看到错误的原因!

这是我的工厂

<cfcomponent output="true" displayname="ObjectFactory">

 <cffunction name="init" access="public" output="true" returntype="ObjectFactory">
  <cfset variables.instance = structNew() />
  <cfreturn this />
 </cffunction>

 <cffunction name="createObj" access="public" output="false" returntype="any">
  <cfargument name="objName" type="string" required="true" />
  <cfswitch expression="#arguments.objName#">
   <cfcase value="abstractCollection">
    <cfreturn createObject('component',"AbstractCollection").init() />
    <cfbreak />
   </cfcase>
   <cfcase value="assignmentCollection">
    <cfreturn createObject('component',"AssignmentCollection").init() />
    <cfbreak />
   </cfcase>
   <cfcase value="salesmanBean">
    <cfreturn createObject('component',"SalesmanBean").init(
     salesmanHasThisDecorations = this.getInstance("assignmentCollection")) />
    <cfbreak />
   </cfcase>
  </cfswitch>
 </cffunction>

 <cffunction name="getInstance" access="public" output="false" returntype="any">
  <cfargument name="objName" type="string" required="true" />
 <!--- Error occurs in the line below --->
  <cfif not structKeyExists(variables.instance, arguments.objName)>
   <cfset variables.instance[arguments.objName] = this.createObj(arguments.objName) />
  </cfif>
  <cfreturn variables.instance[arguments.objName] />
 </cffunction>
</cfcomponent>

2 个答案:

答案 0 :(得分:4)

确保在实例化ObjectFactory时调用init():

<cfset objectFactory = CreateObject("component","ObjectFactory").init()>

仅供参考,init()<cfcomponent>应该有output='false'

仅供参考,您应该在没有“this。”的情况下调用自己的函数,因为如果由于某种原因该函数稍后被声明为私有,它将无法在“this”范围内找到它。

答案 1 :(得分:0)

同意您可能不会调用.init(),因此在访问变量之前不会创建变量。

您还可能希望在init()之外初始化(创建)VARIABLES范围变量。 init()应该更多地用于将值传递到内部CFC范围(VARIABLES范围),而不是在其中创建变量。

<cfcomponent displayname="ObjectFactory">
<cfset variables.instance = structNew() />

 <cffunction name="init" access="public" returntype="ObjectFactory">
  <cfargument name="name" required="yes" type="string">
  <cfset variables.instance.name = arguments.name>
  <cfreturn this />
 </cffunction>

...