MVC Controller Resolver Cache
I recently faced a curious problem: I was using a third party IoC container in an MVC 5 (ASP.NET 4.*) app. In it, I had registered a service with a lifetime of transient, meaning, each resolution would return a different instance.
As you may know, in an MVC controller, there are two ways by which we can resolve a service using the MVC infrastructure:
-
Through the DependencyResolver.Current static property; this returns the IoC container that was registered through DependencyResolver.SetResolver;
-
Or through the Controller.Resolver property, which, I thought, pointed to the same as DependencyResolver.Current.
I was using Controller.Resolver to resolve a service, but, after the first resolution, I would alwas get the same instance! It turns out that, by default, Controller.Resolver does not resolve to the same as DependencyResolver.Current, but instead uses an internal implementation that caches resolved services(DependencyResolver.CurrentCache, an internal property)! This means that it is virtually unusable with any lifetime other than singleton!
There are at least three workarounds:
-
Do not use Controller.Resolver but use DependencyResolver.Current instead;
-
Explicitly set the Controller.Resolver property, either from the controller’s constructor or from a controller factory;
-
Use constructor injection to inject the service into the controller’s constructor.
If you were to ask me, I’d go for option #3.