• Stars
    star
    691
  • Rank 65,435 (Top 2 %)
  • Language
    C#
  • License
    MIT License
  • Created about 8 years ago
  • Updated about 5 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A DDD guestbook example written for ASP.NET Core

Build Status Test Status Test Coverage

Clean Architecture

A starting point for Clean Architecture with ASP.NET Core. Clean Architecture is just the latest in a series of names for the same loosely-coupled, dependency-inverted architecture. You will also find it named hexagonal, ports-and-adapters, or onion architecture.

Give a Star! ⭐

If you like or are using this project to learn or start your solution, please give it a star. Thanks!

Now available as a project template within Visual Studio.

Versions

The master branch is now using .NET Core Version 3.0. If you need a 2.x version use one of these tagged commits:

Learn More

Goals

The goal of this repository is to provide a basic solution structure that can be used to build Domain-Driven Design (DDD)-based or simply well-factored, SOLID applications using .NET Core. Learn more about these topics here:

If you're used to building applications as single-project or as a set of projects that follow the traditional UI -> Business Layer -> Data Access Layer "N-Tier" architecture, I recommend you check out these two courses:

History and Shameless Plug Section

I've used this starter kit to teach the basics of ASP.NET Core using Domain-Driven Design concepts and patterns for some time now (starting when ASP.NET Core was still in pre-release). Typically I teach a one- or two-day hands-on workshop ahead of events like DevIntersection, or private on-site workshops for companies looking to bring their teams up to speed with the latest development technologies and techniques. Feel free to contact me if you'd like information about upcoming workshops.

Design Decisions and Dependencies

The goal of this sample is to provide a fairly bare-bones starter kit for new projects. It does not include every possible framework, tool, or feature that a particular enterprise application might benefit from. Its choices of technology for things like data access are rooted in what is the most common, accessible technology for most business software developers using Microsoft's technology stack. It doesn't (currently) include extensive support for things like logging, monitoring, or analytics, though these can all be added easily. Below is a list of the technology dependencies it includes, and why they were chosen. Most of these can easily be swapped out for your technology of choice, since the nature of this architecture is to support modularity and encapsulation.

The Core Project

The Core project is the center of the Clean Architecture design, and all other project dependencies should point toward it. As such, it has very few external dependencies. The one exception in this case is the System.Reflection.TypeExtensions package, which is used by ValueObject to help implement its IEquatable<> interface. The Core project should include things like:

  • Entities
  • Aggregates
  • Domain Events
  • DTOs
  • Interfaces
  • Event Handlers
  • Domain Services
  • Specifications

Many solutions will also reference a separate Shared Kernel project/package. I recommend creating a separate SharedKernel project and solution if you will require sharing code between multiple projects. I further recommend this be published as a nuget package (more likely privately) and referenced as a nuget dependency by those projects that require it. For this sample, in the interest of simplicity, I've added a SharedKernel folder to the Core project which contains types that would likely be shared between multiple projects, in my experience.

The Infrastructure Project

Most of your application's dependencies on external resources should be implemented in classes defined in the Infrastructure project. These classes should implement interfaces defined in Core. If you have a very large project with many dependencies, it may make sense to have multiple Infrastructure projects (e.g. Infrastructure.Data), but for most projects one Infrastructure project with folders works fine. The sample includes data access and domain event implementations, but you would also add things like email providers, file access, web api clients, etc. to this project so they're not adding coupling to your Core or UI projects.

The Infrastructure project depends on Microsoft.EntityFrameworkCore.SqlServer and Autofac. The former is used because it's built into the default ASP.NET Core templates and is the least common denominator of data access. If desired, it can easily be replaced with a lighter-weight ORM like Dapper. Autofac (formerly StructureMap) is used to allow wireup of dependencies to take place closest to where the implementations reside. In this case, an InfrastructureRegistry class can be used in the Infrastructure class to allow wireup of dependencies there, without the entry point of the application even having to have a reference to the project or its types. Learn more about this technique. The current implementation doesn't include this behavior - it's something I typically cover and have students add themselves in my workshops.

The Web Project

The entry point of the application is the ASP.NET Core web project. This is actually a console application, with a public static void Main method in Program.cs. It currently uses the default MVC organization (Controllers and Views folders) as well as most of the default ASP.NET Core project template code. This includes its configuration system, which uses the default appsettings.json file plus environment variables, and is configured in Startup.cs. The one dependency that you'll see used in this project is StructureMap, which is configured in the Startup.cs class. There are two reasons I prefer StructureMap to the built-in container that ships with ASP.NET Core (and which Microsoft states is only a starting point with minimal functionality). First, the above-mentioned technique for avoiding the need for project references between Web and Infrastructure projects. Second, its WithDefaultConventions convention saves a lot of boilerplate coding when you are wiring up implementations to interfaces that follow a simple naming convention. If for instance I have an INotificationService interface that I want to be resolved using an instance of NotificationService, in ASP.NET Core I would need to add a line of code to add this. With StructureMap's WithDefaultConventions convention, this wireup happens automatically. Any interface named IWhatever will be resolved by a class named Whatever.

The Test Projects

Test projects could be organized based on the kind of test (unit, functional, integration, performance, etc.) or by the project they are testing (Core, Infrastructure, Web), or both. For this simple starter kit, the test projects are organized based on the kind of test, with unit, functional and integration test projects existing in this solution. In terms of dependencies, there are three worth noting:

  • xunit I'm using xunit because that's what ASP.NET Core uses internally to test the product. It works great and as new versions of ASP.NET Core ship, I'm confident it will continue to work well with it.

  • Moq I'm using Moq as a mocking framework for white box behavior-based tests. If I have a method that, under certain circumstances, should perform an action that isn't evident from the object's observable state, mocks provide a way to test that. I could also use my own Fake implementation, but that requires a lot more typing and files. Moq is great once you get the hang of it, and assuming you don't have to mock the world (which we don't in this case because of good, modular design).

  • Microsoft.AspNetCore.TestHost I'm using TestHost to test my web project using its full stack, not just unit testing action methods. Using TestHost, you make actual HttpClient requests without going over the wire (so no firewall or port configuration issues). Tests run in memory and are very fast, and requests exercise the full MVC stack, including routing, model binding, model validation, filters, etc.

More Repositories

1

CleanArchitecture

Clean Architecture Solution Template: A starting point for Clean Architecture with ASP.NET Core
C#
16,284
star
2

GuardClauses

A simple package with guard clause extensions.
C#
3,063
star
3

ApiEndpoints

A project for supporting API Endpoints in ASP.NET Core web applications.
C#
2,934
star
4

SmartEnum

A base class for quickly and easily creating strongly typed enum replacements in C#.
C#
2,178
star
5

Specification

Base class with tests for adding specifications to a DDD model
C#
1,922
star
6

pluralsight-ddd-fundamentals

Sample code for the Pluralsight DDD Fundamentals course by Julie Lerman and Steve "ardalis" Smith
CSS
841
star
7

Result

A result abstraction that can be mapped to HTTP response codes if needed.
C#
819
star
8

CleanArchitecture.WorkerService

A solution template using Clean Architecture for building a .NET Core Worker Service.
C#
720
star
9

kata-catalog

My list of code katas
C#
670
star
10

DesignPatternsInCSharp

Samples associated with Pluralsight design patterns in c# courses.
C#
518
star
11

DDD-NoDuplicates

Some design approaches to enforcing a business rule requiring no duplicates. Domain driven design.
C#
512
star
12

SolidSample

C#
474
star
13

new-software-project-checklist

The ultimate new software project decision/question checklist
443
star
14

ddd-vet-sample

A sample meant to demonstrate domain driven design using a veterinary hospital management system.
C#
305
star
15

OrganizingAspNetCore

Offers several different ways to organize content in ASP.NET Core MVC and Razor Pages projects.
C#
207
star
16

Ardalis.Extensions

Some random C# extension methods I've found useful. Published as Ardalis.Extensions on Nuget.
C#
147
star
17

WebApiBestPractices

Resources related to my Pluralsight course on this topic.
C#
144
star
18

CachedRepository

A sample demonstrating the CachedRepository pattern
C#
104
star
19

HttpClientTestExtensions

Extensions for testing HTTP endpoints and deserializing the results. Currently works with XUnit.
C#
92
star
20

CertExpirationCheck

A simple xUnit C# test showing how to verify a certificate for a domain has at least 30 days before it expires.
C#
79
star
21

DotNetDataAccessTour

A tour of different data access approaches in .NET 8+.
C#
73
star
22

AspNetCoreStartupServices

A simple demo listing all services available to an app at startup
C#
69
star
23

GettingStartedWithFilters

Filters samples associated with MSDN article
C#
67
star
24

AspNetCoreRouteDebugger

An ASP.NET Core Route Debugger implemented as a Razor Page
C#
67
star
25

Ardalis.SharedKernel

Some useful base classes, mainly used with the CleanArchitecture template. Also, a template to make your own SharedKernel nuget package.
C#
56
star
26

MediatRAspNetCore

Sample showing MediatR with ASP.NET Core
C#
50
star
27

DevIQ-gatsby

JavaScript
48
star
28

DomainEventsConsole

A console app showing domain events in action using .NET 5
C#
41
star
29

BuilderTestSample

Show how to use a builder with unit tests.
C#
40
star
30

EFCore.Extensions

Extension methods to make working with EF Core easier.
C#
38
star
31

CSharpGenerics

Some samples using C# generics for a Pluralsight course.
C#
38
star
32

Ardalis.ApiClient

Some classes to make working with APIs easier.
C#
33
star
33

TestPatterns

Examples of approaches to unit testing different kinds of code in C#.
C#
33
star
34

StatePattern

An example of the State design pattern in C#
C#
30
star
35

MinimalWebApi

A minimal Web API for ASP.NET Core
C#
29
star
36

BlazorAuth

A sample showing how to add ASP.NET Core Identity auth options to the basic Blazor app.
C#
27
star
37

EditorConfig

A sample editorconfig file for use with .NET / C# applications
27
star
38

DevResources

A list of links to resources.
26
star
39

NotFoundMiddlewareSample

Middleware for detecting and correcting website 404 errors.
C#
25
star
40

DomainModeling

Some examples showing domain modeling tips and traps
C#
21
star
41

AggregateEvents

A sample showing how to use domain events within aggregates
C#
19
star
42

Specification.EFCore

Some utilities for EF Core to use Specifications
C#
16
star
43

LazyLoading

C#
16
star
44

TestSecureApiSample

A sample showing how to test a secure API endpoint using xunit, identityserver4, and environment variables
JavaScript
15
star
45

EulerCSharpStarter

A starting point for solving Project Euler problems using C#.
C#
14
star
46

EnumAlternative

A sample demonstrating strongly typed C# alternatives to enums.
C#
13
star
47

RouteAndBodyModelBinding

A model binder for ASP.NET Core that supports pulling in values from the route and body of a request.
C#
13
star
48

DoubleDispatchSamples

Some examples of double dispatch in C# and how to use in domain models.
C#
13
star
49

ardalis-com-gatsby

Back end content for ardalis.com running with Netlify and Gatsby.
JavaScript
12
star
50

GildedRoseStarter

A starting point for the Gilded Rose kata using dotnet core, C#, and xunit.
C#
11
star
51

ValueObjectsDemo

C#
10
star
52

MongoDbDotNetHelloWorld

Demonstrating how to get started with MongoDB as quickly as possible in dotnet
C#
10
star
53

TestingLogging

A sample showing how to test logging is working as expected in ASP.NET Core apps.
C#
10
star
54

GuardClauses.Analyzers

A project for holding Roslyn analyzers that leverage Ardalis.GuardClauses
C#
10
star
55

ValidateModel

A very small library/package that includes a model validation attribute for ASP.NET Core projects.
C#
9
star
56

RegExLib.com

Source code for the regexlib.com regular expression library site.
C#
9
star
57

SoftwareQualityWorkshop2020

Public resources supporting private software quality workshops I'm delivering in 2020.
C#
9
star
58

RepoMultiImplementation

C#
8
star
59

MediatREndpointsSample

A sample using MediatR to map endpoints using minimal apis
C#
8
star
60

DomainEventsDemo

A sample project showing how to wire up Domain Events
C#
8
star
61

MessagingDemo

C#
8
star
62

RefactoringKataAttempts2024

C#
8
star
63

AspNetCoreNewIn21

Samples showing what's new in ASP.NET Core 2.1
JavaScript
7
star
64

CSharpPropertiesExamples

Some examples of when and how C# properties work in different application scenarios.
C#
6
star
65

EulerNodeStarter

A starting point for solving Project Euler problems using node.js
JavaScript
6
star
66

RefactoringSamples

C#
6
star
67

UnitTestPerf

Some projects used to demonstrate the performance of different unit testing frameworks for .NET Core
C#
6
star
68

AccessTokenSample

A small sample showing how to create, manage, use access tokens.
C#
6
star
69

IntegrationEventSample

Sample showing Domain Events and Integration Events with Web API 2
C#
6
star
70

azure-cloud-native-book

5
star
71

ExtensionMethodSample

Some simple extension method samples
C#
5
star
72

Cachify

A .NET library to optimize data and reflection-based operations using caching.
PowerShell
5
star
73

Refactoring-To-SOLID-Pluralsight

Resources for my Pluralsight course on Refactoring to SOLID C# Code
C#
5
star
74

CodinGameFall2022

C#
5
star
75

EFCoreOwnedEntityTests

A unit test project that tests owned entities in EF Core
C#
5
star
76

EFCoreStringInterpolationDemo

Showing new EF Core 2.0 feature for raw SQL queries
C#
5
star
77

Diagrams

Text and images from UML and similar diagrams
5
star
78

RedisDotNetHelloWorld

Getting started with Redis in dotnet
C#
5
star
79

WhenAllTest

A simple app showing perf gains of using WhenAll for parallel task execution.
C#
5
star
80

AdventOfCode2022

Working on this: https://adventofcode.com for 2022
C#
4
star
81

ardalis

4
star
82

StructureMapLoggingSample

C#
4
star
83

ConsoleLoggingSample

A sample using NLog to create custom loggers that include app-specific data in the output.
C#
4
star
84

ValidationRules

A collection of validation rules for VS Web Tests
C#
3
star
85

CraftsmanshipCalendarIdeas

Ideas for next year's software craftsmanship calendar
3
star
86

CodinGameSpring2021

C#
3
star
87

Logging

Some logging utilities for .NET Core
C#
3
star
88

MigrateDotNetWithIIS

JavaScript
3
star
89

CastleWindsorSample

A console app showing the basic setup of Castle Windsor for IOC
C#
3
star
90

GeekDinnerSample

An incomplete sample showing clean code and DI in ASP.NET Core
C#
3
star
91

RegExLib

Regexlib.com source
C#
3
star
92

MontyHallMvc

An ASP.NET MVC application that lets users try out the Monty Hall problem and shows their stats.
C#
3
star
93

yarp-passthrough

The simplest YARP ASP.NET Core app that just passes everything through to another domain.
C#
3
star
94

AggregatePatterns

C#
2
star
95

EulerNode

A node.js implementation of Project Euler problems.
JavaScript
2
star
96

TennisGameKatas

C#
2
star
97

AspNetCoreLabs

2
star
98

EFCoreFeatureTests

Tests demonstrating EF Core features across versions.
C#
2
star
99

TestRepo

Just a repo for testing some things
2
star
100

FizzBuzzVS2015

A sample FizzBuzz kata implementation using VS2015
Smalltalk
2
star