2

我的 Singleton 工厂类是这样定义的:

 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(string name) 来初始化 spring IOC 容器,则会发生异常。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

从日志中,它说我不能调用ContextRegistry.GetContext()我的 Singleton 工厂类SpringFactory。但我不知道为什么。

寻找你的答案。

4

1 回答 1

1

从您的构造函数中删除对上下文的调用。

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

static SpringFactory()
{
}

// Some other code

正如例外所说:

根上下文当前正在创建中。您不能调用 ContextRegistry.GetContext()

在创建完成之前,您不能从上下文或上下文 itef 调用引用。

于 2013-12-24T17:41:23.403 回答