Azadeh Khojandi
Azadeh Khojandi

Reputation: 4074

Is there an automated way to find unused views in MVC?

Does any one know a way to find out unused views in project ? with Resharper or without it. any idea which is easier than writing down all the views and go through all controllers and check manually is appreciated :) Thanks

Upvotes: 11

Views: 2908

Answers (1)

Chris Fulstow
Chris Fulstow

Reputation: 41902

With ReSharper you can right-click a Razor view and Find Usages, but you'd have to go through manually and repeat for all views (unless you can hook into ReSharper's API and automate it).

The problem with views of course is that they're late-bound based on a convention defined in the view engine, in the case of the default RazorViewEngine it looks for a corresponding view in ~/Views/{Controller}/{Action} and ~/Views/Shared/{Action}. So it's difficult to tell at design or compile time which views, partials and templates are never used.

You might approch it from the opposite angle: find which views are being used. Then diff this list against all views in the project, evaluate the results (manually and with ReSharper Find Usages) and confirm they're really not being used before finally removing them.

To find the views being used you could customise the RazorViewEngine to log every time it loads a view with CreateView and FindPartialView, e.g.

public class LoggingRazorViewEngine : RazorViewEngine
{
    protected override IView CreateView(
        ControllerContext controllerContext,
        string viewPath,
        string masterPath)
    {
        LogManager.GetLogger("").Debug(viewPath);
        return base.CreateView(controllerContext, viewPath, masterPath);
    }
}

Configure it in global.asax.cs

ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new LoggingRazorViewEngine());

Then extract a list of logged unique view paths to compare against your project's views. Bit of effort involved, but possibly worth if if you've got lots of unused views cluttering up the project.

Upvotes: 12

Related Questions