问题
In my MVC4, .NET4.5 web app using Unity IoC container, in the method IoCContainerFactory.GetControllerInstance() we use ServiceLocator.Current.GetInstance to get the controller instance:
public class IoCControllerFactory : DefaultControllerFactory
{
protected override IController GetControllerInstance(
System.Web.Routing.RequestContext requestContext, Type controllerType)
{
// snip other code
// this is the problem line:
return ServiceLocator.Current.GetInstance(controllerType) as IController;
}
}
But this has been performing too slowly. Using JetBrains DotNetTrace product I've found that ServiceLocator.Current.GetInstance appears to be calling ObjectBuilder2.PolicyList.GetNoDefault more than one million times. How can I figure out why it is making so many calls, and what can I do to fix this problem? Attached screenshot shows the output from dotnetTrace:
And what policy is it trying to get in the method PolicyList.GetNoDefault
? I I knew what policy it was trying to find I could perhaps change that policy so that it does need to be checked so many times.
回答1:
This problem was never solved and we ended up dropping Unity in favor of LightInject, which is a significantly faster IoC implementation, as seen here:
IoC Container Benchmark - Performance comparison
We had similar improvements when we implemented LightInject.
回答2:
I ran into a remotely similar issue, but my problem resulted in a StackOverflowException
. It was caused by a circular dependency between some of my classes.
来源:https://stackoverflow.com/questions/18807355/servicelocator-current-getinstance-causes-excessive-number-of-calls-to-objectbui