Feature Folders in ASP.NET MVC 03 October 2013
If you’ve worked with ASP.NET MVC, you’re no doubt familiar with the default folder structure, which looks something like this:
…and if you’re evolving your project structure, it may even look like this:
Problem is, this structure gets out of hand really quickly. You either have a ton of similarly-named folders in each top-level folder for the main features in your application, or a lot of very verbosely-named classes directly in each folder.
Wouldn’t it be awesome if all of these horizontally-sliced files were instead grouped by feature?
In our current project, Jimmy Bogard and I decided to switch to a model of “feature folders”, where each vertical slice of the project existed—as much as possible—in a single folder. Take a look:
This is a whole lot cleaner to look at. For us, the Solution Explorer was practically useless as we’d need to scroll through dozens and dozens of files only related by role within the system. In this new structure, all files are related by function, and some consistent naming (in our case, by the name of the view) ensures they’re sorted together. Here’s how it works.
Stuff that “just works”
Most of our files work with this pattern automatically. StructureMap does an impeccable job of finding dependencies regardless of where they’re located, and many other files (commands and queries, à la Matt Hinze’s Short Bus) are referenced directly.
The first work we’ll need to do is for the views. We really only want to tell MVC to look for views in a different place than normal, which can be accomplished easily with an extension of the default
public class FeatureViewLocationRazorViewEngine : RazorViewEngine
var featureFolderViewLocationFormats = new
ViewLocationFormats = featureFolderViewLocationFormats;
MasterLocationFormats = featureFolderViewLocationFormats;
PartialViewLocationFormats = featureFolderViewLocationFormats;
Note: If you’re a ReSharper user, it won’t find the views unless you explicitly assign the array of view locations to each property. The project still builds otherwise, but your controllers will have errors next to every call to
PartialView(). See this gist by Jimmy for more details.
Next, tell MVC to use this—and only this—view engine:
…and you’re done! You can now move your Razor views into feature folders alongside your commands, queries, handlers, and validators!
As it stands, we’re keeping our controllers separate, but we’re looking into ways to put those in feature folders, too.
Simplify Client-side Validation…by Adding a Server