title: ASP.NET MVC Custom Route Constraints, Dependency Injection and Unit Testing
body: <p>About this topic, I have asked another question:</p>
  
  <p><a href="https://stackoverflow.com/questions/8308642/asp-net-mvc-custom-route-constraints-and-dependency-injection">ASP.NET MVC Custom Route Constraints and Dependency Injection</a></p>
  
  <p>Here is the current situation: on my ASP.NET MVC 3 App, I have a route constraint defined like below:</p>
  
  <pre><code>public class CountryRouteConstraint : IRouteConstraint {
  
      private readonly ICountryRepository&lt;Country&gt; _countryRepo;
  
      public CountryRouteConstraint(ICountryRepository&lt;Country&gt; countryRepo) {
          _countryRepo = countryRepo;
      }
  
      public bool Match(HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) {
  
          //do the database look-up here
  
          //return the result according the value you got from DB
          return true;
      }
  }
  </code></pre>
  
  <p>I am using this like below:</p>
  
  <pre><code>routes.MapRoute(
      "Countries",
      "countries/{country}",
      new { 
          controller = "Countries", 
          action = "Index" 
      },
      new { 
          country = new CountryRouteConstraint(
              DependencyResolver.Current.GetService&lt;ICountryRepository&lt;Country&gt;&gt;()
          ) 
      }
  );
  </code></pre>
  
  <p>At the unit testing part, I used the below code:</p>
  
  <pre><code>[Fact]
  public void country_route_should_pass() {
  
      var mockContext = new Mock&lt;HttpContextBase&gt;();
      mockContext.Setup(c =&gt; c.Request.AppRelativeCurrentExecutionFilePath).Returns("~/countries/italy");
  
      var routes = new RouteCollection();
      TugberkUgurlu.ReservationHub.Web.Routes.RegisterRoutes(routes);
  
      RouteData routeData = routes.GetRouteData(mockContext.Object);
  
      Assert.NotNull(routeData);
      Assert.Equal("Countries", routeData.Values["controller"]);
      Assert.Equal("Index", routeData.Values["action"]);
      Assert.Equal("italy", routeData.Values["country"]);
  }
  </code></pre>
  
  <p>Here, I cannot figure out how to pass the dependency. Any idea?</p>