Question

As far as I know the DependencyResolver is Thread-Safe, however, running the following code throws a null reference exception in a background thread.

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

Here's the stack trace:

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

I'm aware that the "Service Locator" pattern is an anti-pattern. At this point I'm just trying to understand why this doesn't work.

Any insights would be appreciated.

Thanks!

Was it helpful?

Solution

From the stack trace it is clear that you are using the the Unity.Mvc4 NuGet package, which is some unofficial package and is not published by Microsoft. This package contains a bug. Its UnityDependencyResolver.ChildContainer property calls HttpContext.Current.Items without checking whether HttpContext.Current is null and it causes a NullReferenceException when instances are resolved outside the context of a web request.

So instead of using that unofficial NuGet package, I think you're better off using the official NuGet package.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top