Sponsorship is available! If you’d like to sponsor CodeOpinion.com and have your product or service advertised exclusively (no AdSense) on every post, contact me.This post is in my Fat Controller CQRS Diet series. It demonstrates how to thin your controllers by implementing commands and queries using the MediatR library. Specifically in this post, I’ll look at organizing your code by vertical slices. I’m converting the MusicStore application that’s using ASP.NET Core MVC. All the source code is available on GitHub. If you’re new to this series, here are earlier posts to get up to speed:
Organize by FeatureFeature Slices or Vertical Slices are the terms I’ve heard the most for what I call Organize by Feature. I’ve just always characterized as organizing all relevant code and files from a command or query into a specific folder or hopefully single file. I generally stay away from creating layers so the term Vertical Slices does make a lot of sense. Whatever our feature slice is, it surely makes sense to keep all that code together.
Single FileIf you’ve seen the code related to my Command Pipeline or Notifications posts, then you should already be able to tell where I’m heading in terms of organization. I generally like to keep the command/query and it’s associated handler all within the same file. In the case of our logging handler, I was also keeping it in this file. Pretty simple. One file for everything related to a command or query.
Controllers & ViewsWell almost. What I hadn’t really moved were the controllers or views. So let’s do that now. Controllers are pretty easy since by default they can live anywhere within your project. ASP.NET MVC Core will just pick them up. Let’s work on our Home Query. We will simply create a
HomeControllerwithin our Home.cs file that currently contains our query and our handler. Because we are no longer using the default routing, I’ve added the
HttpGetattribute to the method to keep the route intact to what it was prior.
View LocatorBy default, ASP.NET Core MVC will look in the
~/Views/folder with default conventions. But we want to put our view right along side our
Home.csfile in our Features folder. So I’ve moved all of the view files into our Features folder. Our solution now looks like this: In order to tell ASP.NET where our views are now at, we can implement the
IViewLocationExpanderNow in the
IServiceProvider ConfigureServices(IServiceCollection services)method from our
Startup.cs, we can can configure to use our new locator.