While the proposed @Darin approach works, nested dependencies should stay alive throughout the life of the application. If, for example, the dependency area depends on the request area, then it will work for the first request, and not for each request after that.
You can get around this using a very simple DI wrapper for route restrictions.
public class InjectedRouteConstraint<T> : IRouteConstraint where T : IRouteConstraint { private IDependencyResolver _dependencyResolver { get; set; } public InjectedRouteConstraint(IDependencyResolver dependencyResolver) { _dependencyResolver = dependencyResolver; } public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) { return _dependencyResolver.GetService<T>().Match(httpContext, route, parameterName, values, routeDirection); } }
then create your routes like this
var _dependencyResolver = DependencyResolver.Current; //Get this from private variable that you can override when unit testing routes.MapRoute( "Countries", "countries/{country}", new { controller = "Countries", action = "Index" }, new { country = new InjectedRouteConstraint<CountryRouteConstraint>(_dependencyResolver); } );
EDIT: tried to make it doable.
source share