Unity MVC GetService NullReferenceException thrown in background thread

As far as I know, DependencyResolver is thread safe, however running the following code will throw a link in the 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 know that the "Service Locator" template is an anti-template. At the moment, I'm just trying to understand why this is not working.

Any ideas would be appreciated.

Thank!

+3
source share
1 answer

, Unity.Mvc4 NuGet, Microsoft. . UnityDependencyResolver.ChildContainer HttpContext.Current.Items , HttpContext.Current NullReferenceException, -.

NuGet, , NuGet .

+5

All Articles