为什么我不能在我的单件工厂类中调用ContextRegisty.GetContext()' Springfactory'?

时间:2013-11-04 02:43:38

标签: asp.net spring dependency-injection ioc-container spring.net

我的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(字符串名称)初始化Spring IOC容器 ,将发生异常。例外日志是:

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

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

寻找答案。

1 个答案:

答案 0 :(得分:1)

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

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

static SpringFactory()
{
}

// Some other code

正如例外所说:

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

在创建完成之前,您无法从上下文或上下文中调用引用。