1

我的單身工廠類的定義是這樣的:爲什麼我不能在我的單例工廠類'Springfactory'中調用ContextRegisty.GetContext()?

public sealed class SpringFactory 
     { 
      private static readonly Object ContainerLock=new object(); 
      private static IApplicationContext _applicationContext; 
      // private SpringFactory(){} 

      static SpringFactory() 
      { 
       lock (ContainerLock) 
       { 
        _applicationContext = ContextRegistry.GetContext();   } 
      } 

      public static Object GetObject(string objectId) 
      { 
       try 
       { 
        if (_applicationContext == null) 
        { 
         lock (ContainerLock) 
         { 
          _applicationContext = ContextRegistry.GetContext(); 
         }  
        } 
       } 
       catch (Exception ex) 
       { 
        LogHelper.WriteLog(string.Format("SpringFactory.GetObject({0})",objectId), ex); 
       } 
       return _applicationContext.GetObject(objectId); 
      } 
     } 

但如果我通過Springfactory.getObject(字符串名稱) 的呼叫初始Spring IoC容器,一個異常將被occured.en,異常日誌:

time:2013-11-04 09:49:20,500 [1] 
level:ERROR 
type:logerror [(null)] 
SpringFactory.GetObject(adminFacade) 
System.InvalidOperationException: root context is currently in creation. You must not call ContextRegistry.GetContext() from e.g. constructors of your singleton objects 
    at Spring.Context.Support.ContextRegistry.InitializeContextIfNeeded() 
    at Spring.Context.Support.ContextRegistry.GetContext() 
    at Domain.common.SpringFactory.GetObject(String objectId) in E:\CommercialProjects\huatongMISNew\huatongmis\HuaTongBusinessWeb\Domain\common\SpringFactory.cs:line 50 

從日誌,它說,我不能在我的單身工廠類SpringFactory調用ContextRegistry.GetContext()。但我不知道爲什麼。

尋找答案。

回答

1

從構造函數中移除對上下文的調用。

private IApplicationContext ApplicationContext 
{ 
    lock (ContainerLock) 
    { 
     _applicationContext = ContextRegistry.GetContext(); 
    } 
    return _applicationContext; 
} 

static SpringFactory() 
{ 
} 

// Some other code 

由於異常說:

根上下文目前正在創作。你不能調用ContextRegistry.GetContext()

你不能從上下文或上下文itsef調用引用直到創建完成。

相關問題