Tutorials Microservices with .NET
Implementing User Microservice Domain Layer — Complete Guide
Implementing User Microservice Domain Layer — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of Microservices with .NET on Toolliyo Academy.
On this page
Microservices with .NET · Lesson 13 of 131
Implementing User Microservice Domain Layer
Beginner → Intermediate → Advanced → Professional
Beginner · 1 — Foundations · ~6 min · Module 2: Building User Microservice
What is this?
The Domain layer holds User entity, value objects (Email), domain rules, and repository interfaces — no EF, no HTTP.
Why should you care?
Business rules like “email must be unique” belong here so Application and tests share one truth.
See it live — copy this example
Create a Web API project (dotnet new webapi), paste the code, then run dotnet run.
namespace User.Domain.Entities;
public class UserProfile
{
public Guid Id { get; private set; }
public string Name { get; private set; } = "";
public Email Email { get; private set; } = null!;
public static UserProfile Create(string name, string email)
{
if (string.IsNullOrWhiteSpace(name)) throw new ArgumentException("Name required");
return new UserProfile { Id = Guid.NewGuid(), Name = name.Trim(), Email = Email.Create(email) };
}
}
public interface IUserRepository
{
Task<UserProfile?> GetByIdAsync(Guid id, CancellationToken ct = default);
Task AddAsync(UserProfile user, CancellationToken ct = default);
}
Run Example »
Edit the code and click Run — like W3Schools Try it Yourself.
What happened?
- Create factory method validates invariants.
- IUserRepository is implemented in Infrastructure — Domain only declares the contract.
Try it yourself
- Add UserProfile and Email value object.
- Add IUserRepository interface.
- Write one unit test for UserProfile.Create with invalid email.
- Change a string or route in the example and save — watch Swagger or the RabbitMQ Management UI update.
- Break the code on purpose (remove a semicolon), read the error message, then fix it.
Remember
Domain = entities + rules + interfaces. No EF or ASP.NET references. Factory methods enforce invariants.