🔥 Building a Clean Architecture with Blazor


Today's Sponsor:

HackerPulse — The Ultimate Dev Profile

Don’t send 69 links to share your work - just share one!

Bring together your GitHub, Stack Overflow, and LinkedIn profiles into a single HackerPulse dev profile. Perfect for job applications and networking, HackerPulse gives a complete picture of your skills and projects, all in one place.


Hey Reader,

Today, I'm going to walk you through setting up a Blazor project using Clean Architecture. If you've ever wondered how to structure your Blazor apps to keep them maintainable, scalable, and, well, clean, you're in the right place.

Watch on YouTube 📺

Check out the full tutorial on YouTube to see everything in action 👇

video preview

Getting Started

First, let's fire up Visual Studio 2022 and create a new project. But instead of starting with a Blazor Web App right away, we're going to create a blank solution. Here’s how:

  1. Open Visual Studio and click on "Create a new project."
  2. Search for "Blank Solution" and select it.
  3. Name it something like CleanArchitectureBlazorExample.

This empty solution will be our playground where we'll build out all the layers of our architecture.

Setting Up the Project Structure

Next, let’s organize our solution by adding a Source (src) folder. This is where all our code will live. If you were going to add tests (not in this tutorial), you’d also create a test folder.

Now, let's dive into the Clean Architecture layers.

Understanding Clean Architecture

Clean Architecture is all about organizing your code into different layers:

  1. Domain Layer: This is the core of your app. It contains business logic and entities (like data models).
  2. Application Layer: Here, you'll have things like services and interfaces that use the domain layer.
  3. Infrastructure Layer: This is where you'll handle external stuff like databases, APIs, and file systems.
  4. Presentation Layer: This is the UI of your app, where Blazor comes in.

The idea is that each layer only knows about the layer below it. This keeps things clean and flexible.

Creating the Domain Layer

Let’s start with the Domain layer:

  1. Right-click the src folder > Add > New Project > Class Library.
  2. Name it CleanArchitectureBlazorExample.Domain.
  3. Remove the default Class1.cs file, and let’s add our first entity.

Here’s an example of what your entity might look like:

namespace CleanArchitectureBlazorExample.Domain.Entities
{
    public class Article
    {
        public int Id { get; set; }
        public string Title { get; set; }
        public string Content { get; set; }
        public DateTime PublishedDate { get; set; }
    }
}

This is a basic entity representing a blog article.

Creating the Application Layer

Next up is the Application layer:

  1. Right-click the src folder > Add > New Project > Class Library.
  2. Name it CleanArchitectureBlazorExample.Application.
  3. Just like before, remove Class1.cs.

Here, you might start implementing services or CQRS patterns. For now, let's keep it simple and add a Dependency Injection setup.

using Microsoft.Extensions.DependencyInjection;
namespace CleanArchitectureBlazorExample.Application
{
    public static class DependencyInjection
    {
        public static IServiceCollection AddApplication(this IServiceCollection services)
        {
            // Register your application services here
            return services;
        }
    }
}

This method allows us to add services from the Application layer to our Dependency Injection container.

Creating the Infrastructure Layer

The Infrastructure layer handles the gritty details like data access:

  1. Right-click the src folder > Add > New Project > Class Library.
  2. Name it CleanArchitectureBlazorExample.Infrastructure.

Again, we’ll set up Dependency Injection here:

using Microsoft.Extensions.DependencyInjection;
namespace CleanArchitectureBlazorExample.Infrastructure
{
    public static class DependencyInjection
    {
        public static IServiceCollection AddInfrastructure(this IServiceCollection services)
        {
            // Register your infrastructure services here
            return services;
        }
    }
}

Creating the Presentation Layer

Finally, let’s set up the Presentation layer using Blazor:

  1. Right-click the src folder > Add > New Project > Blazor WebAssembly App.
  2. Name it CleanArchitectureBlazorExample.WebUI.

In the Program.cs, we’ll hook everything up:

using CleanArchitectureBlazorExample.WebUI.Server.Components;
using CleanArchitectureBlazorExample.Application;
using CleanArchitectureBlazorExample.Infrastructure;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddRazorComponents();
builder.Services.AddApplication();
builder.Services.AddInfrastructure();
var app = builder.Build();
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseAntiforgery();
app.MapRazorComponents

This code adds the Application and Infrastructure services to the Blazor project.

Conclusion

And that’s it! You’ve set up a basic Clean Architecture with Blazor. This structure will make your app easier to maintain and scale over time.

If you’re interested in diving deeper into patterns like CQRS or the Mediator pattern, let me know, and I’ll create more tutorials on those topics.

Happy coding and have an awesome weekend!

Take care,

Patrick

PS: Need help understanding .NET & Blazor? There are two ways I can help you with:

  1. Check out the .NET Web Academy, which provides masterclasses and a supportive community of like-minded developers.
  2. I'm open to coaching. If you need specific help, reply to this email and we'll figure something out.

PPS: Would you like to sponsor this newsletter? Click here. 💌


Patrick God

Become a .NET & Blazor expert with weekly tutorials featuring best practices and the latest improvements, right in your inbox.

Read more from Patrick God
video preview

Hey friend, I just released a new video and I think you’ll enjoy it. In the video, I ask GitHub Copilot to build a .NET Web API using a short, vague prompt. The result works, but the structure feels random and messy. Then I run the same idea again with a stronger prompt that forces a clean structure. Feature folders. Vertical slice. Mediator. Fluent Validation. The difference is night and day. Watch the video here 👇 Enjoy the breakdown and let me know what you think. Take care, Patrick P.S....

video preview

Hey friend, I just released a new video showing a better way to use GitHub Copilot in real .NET projects. Watch it here 👇 If you ever felt like Copilot starts strong but then your code slowly turns into chaos, you’re not alone. It happens to most developers when they start using AI without giving it the right guidance. In the video, I show you one simple file you can add to your project that keeps your code clean, structured, and consistent. No guessing. No random patterns. Just a clear...

video preview

Hey friend, I just published a new video that walks you through how to upgrade to .NET 10. Watch it here 👇 If you're already trying the update, you may have seen this: the app builds no errors but… Blazor doesn't load That happened in my project too. And the fix is small, but easy to miss. In the video, I show: how to update the target frameworks how to update NuGet packages what changed for Blazor and how to fix the missing static assets issue No hype. Just a clear step-by-step walkthrough....