Monday, 14 December 2015

Feature Folders in ASP.NET 5 (RC1) with MVC 6

Feature folders are a great way of structuring an MVC project in order to quickly and easily find the files for areas of your website.

You can turn a typical structure like this:

- Website
  + Content
  + Controllers
  + Models
  + Views

in to this:
- Website
  - Features
    - Portfolio

This has been possible for a while now, however the API has changed a bit with ASP.NET 5 (as well as all the beta versions). Currently in ASP.NET 5 RC1 this is how you do it:

Create a new view engine, something like:


public class FeatureViewLocationRazorViewEngine : RazorViewEngine
 private readonly string[] _featureFolderViewLocationFormats;

  public FeatureViewLocationRazorViewEngine(IRazorPageFactory pageFactory, IRazorViewFactory viewFactory, IOptions<RazorViewEngineOptions> options, IViewLocationCache viewLocationCache)
  :base(pageFactory, viewFactory, options, viewLocationCache)
  _featureFolderViewLocationFormats = new[]

  public override IEnumerable<string> ViewLocationFormats => _featureFolderViewLocationFormats;
Then modify the startup file:
public void ConfigureServices(IServiceCollection services)
 services.AddSingleton<IRazorViewEngine, FeatureViewLocationRazorViewEngine>();
That's it!