Unity MVC GetService在后台线程抛出NullReferenceException

Ada*_*dam 3 multithreading unity-container service-locator asp.net-mvc-3

据我所知,DependencyResolver是线程安全的,但运行以下代码会在后台线程中引发空引用异常.

public interface ITest {

}
public class Test : ITest {

}

//this works fine
var service = DependencyResolver.Current.GetService<ITest>();

var t1 = Task.Run(() => {
   //This throws a Null Reference exception.
   // note that DependencyResolver.Current is NOT null.  
   // The exception occurs in GetService
   var s1 = DependencyResolver.Current.GetService<ITest>();
});
Task.WaitAll(t1);
Run Code Online (Sandbox Code Playgroud)

这是堆栈跟踪:

at Unity.Mvc4.UnityDependencyResolver.get_ChildContainer()
at Unity.Mvc4.UnityDependencyResolver.IsRegistered(Type typeToCheck)
at Unity.Mvc4.UnityDependencyResolver.GetService(Type serviceType)
at System.Web.Mvc.DependencyResolverExtensions.GetService[TService](IDependencyResolver resolver)
at System.Threading.Tasks.Task.InnerInvoke()
at System.Threading.Tasks.Task.Execute()
Run Code Online (Sandbox Code Playgroud)

我知道"服务定位器"模式是一种反模式.在这一点上,我只是想了解为什么这不起作用.

任何见解将不胜感激.

谢谢!

Ste*_*ven 5

从堆栈跟踪中可以清楚地看到,您使用的是Unity.Mvc4 NuGet包,这是一些非官方的包,不是由Microsoft发布的.这个包包含一个bug.它的UnityDependencyResolver.ChildContainer属性调用时HttpContext.Current.Items不检查是否HttpContext.Current为null,并且它会导致NullReferenceException在Web请求的上下文之外解析when实例.

所以不要使用那个非官方的NuGet包,我认为你最好使用官方的NuGet包.