multithreading - Unity MVC GetService在后台线程抛出NullReferenceException

标签 multithreading asp.net-mvc-3 unity-container service-locator

据我所知,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);

这是堆栈跟踪:

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()

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

如有任何见解,我们将不胜感激。

谢谢!

最佳答案

从堆栈跟踪可以清楚地看出您正在使用 Unity.Mvc4 NuGet包,这是一些非官方的包,不是微软发布的。这个包包含一个错误。它的 UnityDependencyResolver.ChildContainer 属性调用 HttpContext.Current.Items 而不检查 HttpContext.Current 是否为 null,它会导致 NullReferenceException 当实例在 Web 请求的上下文之外解析时。

因此,与其使用非官方的 NuGet 包,我认为你最好使用 official NuGet package .

关于multithreading - Unity MVC GetService在后台线程抛出NullReferenceException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21681247/

相关文章:

java - java.util 上的并发任务。从 BlockingQueue 轮询的多线程问题

c# - mvc 3 Html.EditorFor 添加 html 属性不起作用

inversion-of-control - 统一框架: How to Instantiate two classes from the same Interface?

.net - 使用 DI 传递同一接口(interface)的多个实现

c# - 安全使用 'HttpContext.Current.Cache'

java - 如何并行运行万无一失的测试,同时强制某些测试按顺序运行?

c# - 运行最大线程 : Automatic performance adjustment

带有自定义参数的 Html.DropDownListFor()

c# - 想在 mvc 中显示来自两个不同 sql 表的数据

c# - 选择性地统一解决同一接口(interface)的依赖关系