Removing duplication of code for calls to "RouteCollection.MapRoute()" and "AreaRegistrationContext.MapRoute()"
Basically as the title says when using Areas in ASP.NET MVC2.0 I've ended up with the following "MapRoute" handling code being duplicated for "RouteCollection" and AreaRegistrationContext". Both objects are outside of my control (i.e. in the .NET MVC framework) but don't appear to inhereit from any common interface / base class. Can anyone recommend a way to remove the code duplication in this situation?
public void Map(RouteCollection routes)
{
if (Details != null)
{
if (Namespaces != null)
routes.MapRoute(Name, Url, Details, Namespaces);
else
{
routes.MapRoute(Name, Url, Details);
}
}
else
{
if (Namespaces != null)
routes.MapRoute(Name, Url, Namespaces);
else
{
routes.MapRoute(Name, Url);
}
}
}
public void Map(AreaRegistrationContext context)
{
if (Details != null)
{
if (Namespaces != null)
context.MapRoute(Name, Url, Details, Namespaces);
else
{
context.MapRoute(Name, Url, Details);
}
}
else
{
if (Namespaces != null)
context.MapRoute(Name, Url, Namespaces);
else
{
context.MapRoute(Name, 开发者_运维百科Url);
}
}
}
Not sure if this helps, but I actually went a different way with route registration. Instead of using areas this way, I actually created an interface IRouteRegistrar
which I can build order registrars for. My example is specific to MEF, but there is no reason you can't use the same mechanism for any other IoC/SL implementation:
/// <summary>
/// Defines the required contract for implementing a route registrar.
/// </summary>
public interface IRouteRegistrar
{
#region Methods
/// <summary>
/// Registers any required routes.
/// </summary>
/// <param name="route">The route collection to register routes with.</param>
void RegisterRoutes(RouteCollection route);
#endregion
}
By abstracting the route registration into this simple interface, I find it a lot more modular and testable.
/// <summary>
/// Registers any required routes with the routing system.
/// </summary>
[ExportBootstrapperTask("RegisterRoutes")]
public class RegisterRoutesBootstrapperTask : IBootstrapperTask
{
#region Methods
/// <summary>
/// Runs the task.
/// </summary>
/// <param name="container"></param>
public void Run(CompositionContainer container)
{
Throw.IfArgumentNull(container, "container");
var registrars = container
.GetExports<IRouteRegistrar, IOrderedMetadata>()
.OrderBy(r => r.Metadata.Order)
.Select(r => r.Value);
var routes = RouteTable.Routes;
foreach (var registrar in registrars)
registrar.RegisterRoutes(routes);
}
#endregion
}
精彩评论