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
        Index.cshtml
        Index.js
        IndexViewModel.cs

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:

FeatureViewLocationRazorViewEngine.cs

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[]
   {
   "~/Features/{1}/{0}.cshtml",
   "~/Features/{1}/{0}.vbhtml",
   "~/Features/Shared/{0}.cshtml",
   "~/Features/Shared/{0}.vbhtml"
   };
 }

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

No comments:

Post a comment