據我所知,DependencyResolver是線程安全的,但是,運行以下代碼會在後臺線程中拋出一個空引用異常。Unity MVC GetService在後臺線程拋出NullReferenceException
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()
我知道,「服務定位器」模式是反模式。在這一點上,我只是想明白爲什麼這不起作用。
任何見解,將不勝感激。
謝謝!
發現這個:http://www.prowareness.com/blog/tag/nullreferenceexception/所以顯然asp.net mvc依賴於HttpContext.Current,這就是爲什麼這不是在我的MVC應用程序工作。 – Adam