Nat*_*end 2 c# dependency-injection unity-container asp.net-web-api asp.net-web-api2
我们有一个使用Unity 2.1.505.0的应用程序.我们的应用程序使用Web.API和自定义DependencyResolverAdapter
来为我们的API控制器启用依赖注入.在这个适配器里面,我们调用了CreateChildContainer()
方法IUnityContainer
.但是,这个电话间歇地抛出一个NullReferenceException
:
在什么情况下此方法会抛出NullReferenceException? 堆栈跟踪没有显示任何明显的原因:
at Microsoft.Practices.Unity.UnityContainer..ctor(UnityContainer parent)
at Microsoft.Practices.Unity.UnityContainer.CreateChildContainer()
at MyApp.DependencyResolverAdapter.BeginScope() in C:\ResCollection\CropProtection\MyApp\MyApp\DependencyResolverAdapter.cs:line 43
at System.Net.Http.HttpRequestMessageExtensions.GetDependencyScope(HttpRequestMessage request)
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)
at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)
Run Code Online (Sandbox Code Playgroud)
奇怪的是,在做了"清洁解决方案"后,应用程序正常工作约20-30秒; 控制器由Unity正确解决,解析器似乎正在完成其工作.然后NullReferenceException
抛出,并且在应用程序的生命周期的剩余时间内没有成功解析控制器.重新运行应用程序(不先清除)会在第一次解析控制器时立即导致此错误.
如果你看一下代码的UnityContainer..ctor(UnityContainer parent)
,其中唯一的地方NullReferenceException
可能发生在这一行:
parent.lifetimeContainer.Add(this);
Run Code Online (Sandbox Code Playgroud)
哪个在里面if (parent != null)
,所以这里唯一可以为null的是parent.lifetimeContainer
.lifetimeContainer
初始化 InitializeBuilderState
,从构造函数调用,并且它在Dispose
方法中设置的唯一其他位置.
因此错误可能是因为父容器已经被处理掉了.
这可能是Unity中的一个错误; CreateChildContainer
应检查容器是否已经处理过,ObjectDisposedException
如果有,则扔掉.
归档时间: |
|
查看次数: |
961 次 |
最近记录: |