2009-07-19 64 views
1

我收到此错误为什么依赖项注入在我的CF工厂对象中失败?

元素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> 

回答

4

确保您调用的init()当实例的ObjectFactory:

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

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

仅供参考,您应该在没有“this”的情况下调用你自己的函数,因为如果由于某种原因该函数稍后被声明为私有函数,那么它就赢了在'这个'范围内找不到它。

0

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

您还可能想要在init()之外初始化(创建)VARIABLES作用域变量。为了将值传递给内部CFC作用域(VARIABLES作用域),应该使用init(),而不是在其中创建变量。

<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> 

... 
+0

我是这样解决的: mrt181 2009-07-24 10:17:41