2009-07-19 30 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