An Opinionated Solution Template

An Opinionated Solution Structure For .Net

Anyone who has worked with me in the last four to five years has probably heard me rant about solution structure and design at least once. I like things to be in logical places and I like to be able to find things quickly. I also love separation of concerns. The Domain model should have no idea how it is persisted, the API endpoints shouldn't care about implementation, and the Core Logic should have the absolute minimum of Domain Logic. Why? Because it makes things clearer, easier to test, and simpler to extend.

Time after time I have seen projects fall apart because at least one of those things wasn't in place. Either the Controllers were thicker than Chicago Deep Dish pizza or the Domain model knew nothing about the Domain logic and only cared about Persistence. All of that was usually compounded by the lack of Unit Tests. How can I ensure that I am pushing correct code without knowing what correct is? All of this has culminated in a Project structure that I use in pretty much every project now:

  • API/Service
  • Core Logic
  • Domain models and Logic
  • Persistence
  • Tests

Each of these Projects has a reason for existence and tackles some part of the whole. Even with these things in place, I have an amount of flexibility here that allows me to tackle most problems.

API/Service Layer

The API or Service Layer is where requests enter the system. This is where the application will determine the basic Authorization and Authentication for requests. Domain Logic often has its own Authorization logic beyond the does this user have the required role authorization. What this layer does do is DTO transformation of Requests and Responses and decides what Core Logic to run. The Service Layer should be the lightest layer of your application.

Core Logic Layer

The Core Logic Layer is where business logic truly begins. Typically, this is where I would put Queries, Commands, and Events. No, I do not like Service classes; they end up huge and often include a bunch of dependencies that only matter on some functions. They quickly become harder to reason about unless properly maintained and culled frequently. CQRS Handlers typically allow for much more targeted code and are generally easier to reason about and test.

I have a few things I like to do, regardless of what I'm using to do my CQRS. Someone familiar with Vogen will notice a departure from guidance that I give later in this blog. The Vogen .From function will throw if the input is invalid. I accept that in this very specific place because there are other ways of ensuring the Guid coming in is valid. Something I would expect to see in the Service Layer.

public class GetItem {
    // record structs are nice here because they reduce allocations
    public readonly record struct ById {
        // ValueObject because I have Primitive Obsession
        public ItemId Id { get; }

        // private constructor to prevent bad query states
        private ById(ItemId id) {
            Id = id;
        }

        // Factory method to hide away all the validation logic
        public static ById From (Guid rawValue) {
            // Checks here
            return new (ItemId.From(rawValue));
        }
    }

    internal class Handler : IQueryHandler<ById, Item> {
        // I am using a made up IQueryHandler interface here instead
        // of the IRequestHandler from that one popular library
        public async Task<Result<Item>> Handle(ById query,
            CancellationToken cancellationToken = default) {
            // Logic goes here
        }
    }
}

Looking at the example above, I have comments explaining much of my thought process. There are a few other things worth calling out explicitly:

  1. I use a class to wrap all this logic together. That means to create a ById query, the external call looks like GetItem.ById.From(guid);. Anybody reading from the controller or test can see that I am trying to Get an Item By Id using a Guid.
  2. I use Result objects. If you are unfamiliar with FluentResults, you should look into it. It provides an abstraction around both Success and Failure that is very helpful. Throwing Exceptions is more expensive, and you can create specific Errors much like you can create specific Exceptions.
  3. I like to make the Handler class internal. That hides it from the API specifically so that nobody can misuse it. To make it testable, you just need a single [assembly:InternalsVisibleTo("the test project")] somewhere in the Core project.

Domain Logic Layer

Your Entities exist in the Domain Layer. The definitions for what Entities look like and what operations they have are here. If you have a Car that needs to be able to Drive, the Car entity and its Drive function will be here somewhere. If you are going to use Specifications, this is where I would put them.

What you won't find here is "How to map field X to database column y". My expectation is that the Domain will know how to do things in the Domain and the external system will have to take care of itself. That said, if you are going to use the Repository pattern, I often find it helpful to define the Interfaces for the Repositories here. If I'm using Repositories I will often include an overload that has a projection parameter so that the caller can control the shape of their response.

public interface IRepository<TEntity, TEntityId>{
    Task<TProjection?> GetById<TProjection>(TEntityId id, Expression<Func<TEntity, TProjection>> projection);
    Task<IList<TProjection?>> GetBy<TProjection>(Specification<TEntity> spec, Expression<Func<TEntity, TProjection>> projection);
    Task Delete(TEntityId id);
    Task Delete(Specification<TEntity> spec);
}

public class CarRepository(DataContext context): IRepository<Car, CarId> {
    public async Task<TProjection> GetById<TProjection>(CarId id, Expression<Func<Car, TProjection>> projection) {
        return context.Cars.Where(c => c.CarId == id).Select(projection).FirstOrDefaultAsync();
    }

    /*... Rest of the implementation here ...*/
}

Another thing you will often see in my Domain Layer is the use of Value Objects. They give you another layer of type safety. A Driver and a Car may both be using Guids for their IDs, but I will get a compile-time failure from Car.Id == Driver.Id. This completely removes an entire class of defects. While you can write your own, tools like the Vogen library make it very simple to create Value Objects. What that looks like is:

// Defines helpers that will be generated to handle Converting to JSON or EFCore
[ValueObject<Guid>(Conversions.EfCoreValueConverter | Conversions.SystemTextJson)]
// Partial so that the Vogen source generators can do their work.
public readonly partial record struct CarId
{
    // Convenience method to create a new CarId
    public static CarId New() => From(Guid.NewGuid());

    // Vogen checks if a Validate method returning Validation exists
    // and will call it as part of the flow
    private static Validation Validate(Guid input)
    {
        return input == Guid.Empty ? Validation.Invalid("CarId cannot be empty") : Validation.Ok;
    }
}

One of the trickiest things here is the readonly partial record struct, .Net is very particular about this ordering. Using Record Structs has some very powerful benefits. Because they are value types, a CarId doesn’t need its own heap allocation the way a class-based wrapper would. It lives inline in whatever contains it, whether that’s a local on the stack or a field on an entity, which means less GC pressure. This can be impactful in the critical path or high-throughput situations, though you’ll want to avoid boxing them (for example, by casting to an interface or object). Using a readonly record or struct gives you compile-time safety checks that you aren't overwriting a value.

Persistence Layer

In my opinion, the Persistence Layer is tied with the Domain Layer for the second most important, right after testing. Here is where we abstract away the storage mechanisms; things that are very expensive to change later. If you are using Blob Storage or a File System on disk, the Business Logic shouldn't care but Persistence should. Persistence is the only place that cares if you are using PostgreSQL, Microsoft SQL Server, or MySQL or even some horrible hodgepodge of them all.

That last sentence is the only reason I really use the Repository pattern still. I can hide the fact that I am using a bunch of different Data Contexts or file structures away. All the complexity ends up in the Persistence Layer and the Domain never needs to know.

Testing Layer

This layer has the most opinions. It's the first layer that management will tell you to cut when time is short. It is the one layer here that is completely not optional. You can combine any other layer and usually things will turn out just fine. You can omit any other layer and it will probably be OK. Omit tests and prepare for failure. I have the fewest things to say about this layer too, because it is so opinionated and important. You must find what works for you and do that.

For me, I am a big believer in XUnit, NSubstitute, Bogus, and Reqnroll. Reqnroll as the first pass in tests makes a lot of sense in an Enterprise environment where you can show your actual testing methodology to your business person and have them agree. NSubstitute works as a Spy and Mocking framework with an API that is fairly intuitive and easy to use. Bogus is a port of the wildly popular Faker library that generates realistic looking test data. XUnit runs my tests. Put all those things together and you can cover so much ground with ease.

Final Words

This has been a relatively long article for me to write. It took well over a week to put everything together and make my thoughts make sense. I've had to stop and restart this article several times. In the end, I took all of my own advice and created a dotnet new template that you can use. I put the code here for anybody to use. That link includes instructions on how to install the template and how to use it. I am dog-fooding my template in my own personal projects. In fact, there is a very good possibility that the Static Site Generator I wrote for this blog may end up refactored as a CLI app that runs on my computer.