English
Files and registration
Step 1. Store files on disk
Why. Attachments and avatars are files, and files do not belong in the database: they would make backups huge and every read slow. Chatex keeps them in a folder on disk — /var/lib/chatex/uploads on the server, .uploads in the repository during development — and the database stores only their storage path.
The danger of files is path traversal. If a storage path ever contained ../../etc/passwd, Path.Combine(root, path) would point outside the upload folder. Chatex closes this door twice:
- the storage itself picks every path, from the date and a new UUID (
2026/11/0199f3c2…), so client file names never become paths; - every path is resolved to a full path and must still start with the root folder; otherwise the call fails.
Do. Create the folder Storage with the settings class and the storage:
cs
namespace Chatex.Data.Storage;
public sealed class FileStorageOptions
{
/// <summary>Directory that holds all uploads, outside the web root (production: <c>/var/lib/chatex/uploads</c>).</summary>
public string RootPath { get; set; } = "";
}cs
using Chatex.Data.Abstractions;
using Microsoft.Extensions.Options;
namespace Chatex.Data.Storage;
/// <summary>Keeps files on the local disk under <see cref="FileStorageOptions.RootPath"/>/yyyy/MM/{guid}.</summary>
internal sealed class LocalFileStorage(IOptions<FileStorageOptions> options, TimeProvider timeProvider) : IFileStorage
{
private readonly string _root = Path.GetFullPath(options.Value.RootPath);
public async Task<string> SaveAsync(Stream content, CancellationToken cancellationToken = default)
{
var now = timeProvider.GetUtcNow();
var storagePath = $"{now:yyyy}/{now:MM}/{Guid.CreateVersion7():N}";
var fullPath = ToFullPath(storagePath);
Directory.CreateDirectory(Path.GetDirectoryName(fullPath)!);
try
{
await using var file = new FileStream(fullPath, FileMode.CreateNew, FileAccess.Write, FileShare.None, 81920, useAsync: true);
await content.CopyToAsync(file, cancellationToken);
}
catch
{
File.Delete(fullPath);
throw;
}
return storagePath;
}
public Task<Stream> OpenReadAsync(string storagePath, CancellationToken cancellationToken = default)
{
Stream stream = new FileStream(ToFullPath(storagePath), FileMode.Open, FileAccess.Read, FileShare.Read, 81920, useAsync: true);
return Task.FromResult(stream);
}
public Task DeleteAsync(string storagePath, CancellationToken cancellationToken = default)
{
File.Delete(ToFullPath(storagePath));
return Task.CompletedTask;
}
private string ToFullPath(string storagePath)
{
var fullPath = Path.GetFullPath(Path.Combine(_root, storagePath));
if (!fullPath.StartsWith(_root + Path.DirectorySeparatorChar, StringComparison.Ordinal))
{
throw new ArgumentException($"Storage path '{storagePath}' points outside the storage root.", nameof(storagePath));
}
return fullPath;
}
}IOptions<FileStorageOptions>is the options pattern of .NET: settings are a class, filled from configuration, and injected._rootis computed once, as a full path.FileMode.CreateNewfails if the file already exists — with a fresh UUID it never does, but if it did, nothing would be overwritten.useAsync: trueopens the file for asynchronous I/O, so a slow disk does not block a thread of the web server; 81920 bytes is the buffer sizeCopyToAsyncuses by default.- A failed upload leaves no half-written file: the
catchdeletes it and rethrows. ToFullPathis the traversal guard.Path.GetFullPathresolves..segments; the checkStartsWith(_root + separator, StringComparison.Ordinal)compares character by character, without culture rules.
Step 2. A health check
Why. On the server, the deployment of topic 24 starts the new version and asks GET /health whether it works; if not, it rolls back. "Works" means above all that the database is reachable. ASP.NET Core has a health check framework; the data layer contributes the database check.
Do. Add the package:
powershell
dotnet add Source/Chatex.Data package Microsoft.Extensions.Diagnostics.HealthChecksxml
<Project Sdk="Microsoft.NET.Sdk">
<ItemGroup>
<PackageReference Include="EFCore.NamingConventions" />
<PackageReference Include="Microsoft.AspNetCore.Identity.EntityFrameworkCore" />
<PackageReference Include="Microsoft.Extensions.Diagnostics.HealthChecks" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design">
<!-- ... -->
</PackageReference>
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" />
</ItemGroup>
</Project>cs
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Diagnostics.HealthChecks;
namespace Chatex.Data;
/// <summary>
/// Runs <c>SELECT 1</c> on a plain connection. It deliberately bypasses the EF execution strategy: retrying a dead
/// database for half a minute would only delay the 503 that tells the deploy to roll back.
/// </summary>
internal sealed class DatabaseHealthCheck(ChatexDbContext db) : IHealthCheck
{
public async Task<HealthCheckResult> CheckHealthAsync(HealthCheckContext context, CancellationToken cancellationToken = default)
{
try
{
var connection = db.Database.GetDbConnection();
await connection.OpenAsync(cancellationToken);
try
{
await using var command = connection.CreateCommand();
command.CommandText = "SELECT 1";
await command.ExecuteScalarAsync(cancellationToken);
}
finally
{
await connection.CloseAsync();
}
return HealthCheckResult.Healthy();
}
catch (Exception ex) when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested)
{
return HealthCheckResult.Unhealthy("The database cannot be reached.", ex);
}
}
}The check runs SELECT 1 on a plain connection, past the retry policy of EF Core, as the comment explains: a health check must answer quickly and honestly, not hide a dead database behind 30 seconds of retries. The exception filter when (ex is not OperationCanceledException || !cancellationToken.IsCancellationRequested) treats every failure as "unhealthy", except a cancellation that the caller asked for.
Step 3. Register the data layer
Why. Every class of the data layer gets its dependencies through its constructor; none of them creates another. Somebody has to assemble the graph — that is the job of the dependency injection container of .NET. Each layer of Chatex registers its own services in one extension method, so the application only calls AddData, and later AddCore and AddApi.
The lifetime of each service matters:
| Lifetime | Services | Why |
|---|---|---|
| singleton — one for the whole application | TimeProvider, TimestampInterceptor, IFileStorage | they keep no per-request state |
| scoped — one per scope (an HTTP request, a SignalR call, a test step) | ChatexDbContext, every repository, IUnitOfWork | they must share the same context, so that one SaveChangesAsync commits the changes of all repositories of the request |
Do. Extend DependencyInjection.cs from topic 4 with AddData (new lines in green):
cs
using Chatex.Data.Abstractions;
using Chatex.Data.Entities;
using Chatex.Data.Interceptors;
using Chatex.Data.Repositories;
using Chatex.Data.Storage;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
namespace Chatex.Data;
public static class DependencyInjection
{
/// <summary>
/// Registers the DbContext, repositories, unit of work and the Identity stores for <see cref="User"/>.
/// Identity options (password rules, lockout) and token providers are configured by the caller.
/// </summary>
public static IServiceCollection AddData(
this IServiceCollection services, string connectionString, Action<FileStorageOptions> configureStorage)
{
services.TryAddSingleton(TimeProvider.System);
services.AddSingleton<TimestampInterceptor>();
services.AddOptions<FileStorageOptions>()
.Configure(configureStorage)
.Validate(o => !string.IsNullOrWhiteSpace(o.RootPath), "Storage root path is not configured.")
.ValidateOnStart();
services.AddSingleton<IFileStorage, LocalFileStorage>();
services.AddDbContext<ChatexDbContext>((sp, options) =>
{
Configure(options, connectionString);
options.AddInterceptors(sp.GetRequiredService<TimestampInterceptor>());
});
services.AddIdentityCore<User>()
.AddRoles<IdentityRole<Guid>>()
.AddEntityFrameworkStores<ChatexDbContext>();
services.AddScoped<IUnitOfWork, UnitOfWork>();
services.AddScoped<IUserRepository, UserRepository>();
services.AddScoped<IRefreshTokenRepository, RefreshTokenRepository>();
services.AddScoped<IChatRepository, ChatRepository>();
services.AddScoped<IChatMemberRepository, ChatMemberRepository>();
services.AddScoped<IMessageRepository, MessageRepository>();
services.AddScoped<IAttachmentRepository, AttachmentRepository>();
// Readiness: /health answers 503 while the database cannot be reached.
services.AddHealthChecks().AddCheck<DatabaseHealthCheck>("database", timeout: TimeSpan.FromSeconds(5));
return services;
}
/// <summary>
/// Transient failures (a dropped connection, a failover) are retried. Explicit transactions must go through
/// <see cref="IUnitOfWork.ExecuteInTransactionAsync{T}"/>, which replays the whole unit of work on a retry.
/// </summary>
internal static void Configure(DbContextOptionsBuilder options, string connectionString) =>
options.UseNpgsql(connectionString, npgsql => npgsql.EnableRetryOnFailure()).UseSnakeCaseNamingConvention();
}TryAddSingleton(TimeProvider.System)registers the real clock only if noTimeProvideris registered yet. A test that registers aFakeTimeProviderfirst keeps its fake clock.AddOptions<FileStorageOptions>()…ValidateOnStart()— the storage settings are validated when the application starts. A missing upload folder fails the start with a clear message, instead of the first upload hours later.AddDbContextregisters the context as scoped. Its configuration uses the sharedConfigurefrom topic 4 and adds the interceptor, taken from the container:(sp, options) => …receives the service providersp.AddIdentityCore<User>()registers Identity'sUserManager<User>and the password hasher, andAddEntityFrameworkStores<ChatexDbContext>()tells Identity to keep users in our context. Identity therefore shares the request's context and its transactions, which is what makes registration in one transaction possible (topic 8). The Identity options — password rules, lockout — belong to the business layer and are set inAddCore(topic 7).AddHealthChecks().AddCheck<DatabaseHealthCheck>(...)adds the check with a 5-second timeout; the endpoint/healthis mapped in topic 13.- The comment on
Configurenow refers toIUnitOfWork.ExecuteInTransactionAsyncand theusing Chatex.Data.Abstractionsmakes the reference resolvable.
Check
dotnet build succeeds, and the data project now matches the reference except for the order of PackageReference lines:
powershell
git diff --no-index Source/Chatex.Data D:\Work\Chatex-Reference\Source\Chatex.DataIgnore the folders bin and obj and the file names of the migration.
Step 4. Try the data layer
Why. The data layer is complete, but nothing uses it yet. As in topic 3, a small program outside the repository shows it at work — this time against the real database, through the same AddData the API will call.
Do. In your playground folder (D:\Work\Playground), create data.cs. Fix the path in the first line if your repository is elsewhere.
cs
#:project D:\Work\Chatex\Source\Chatex.Data\Chatex.Data.csproj
#:property PublishAot=false
using Chatex.Data;
using Chatex.Data.Abstractions;
using Chatex.Data.Entities;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
var services = new ServiceCollection();
services.AddLogging();
services.AddData(
"Host=localhost;Port=5432;Database=chatex;Username=postgres;Password=postgres",
o => o.RootPath = Path.Combine(Path.GetTempPath(), "chatex-playground"));
await using var provider = services.BuildServiceProvider();
// One scope = one unit of work, like one HTTP request.
await using (var scope = provider.CreateAsyncScope())
{
var users = scope.ServiceProvider.GetRequiredService<UserManager<User>>();
var alice = new User { UserName = "alice", Email = "[email protected]" };
var bob = new User { UserName = "bob", Email = "[email protected]" };
Console.WriteLine($"Create alice: {(await users.CreateAsync(alice, "Passw0rd!")).Succeeded}");
Console.WriteLine($"Create bob: {(await users.CreateAsync(bob, "Passw0rd!")).Succeeded}");
var chat = new Chat
{
Type = ChatType.Direct,
DirectKey = Chat.MakeDirectKey(alice.Id, bob.Id),
CreatedById = alice.Id,
};
chat.Members.Add(new ChatMember { UserId = alice.Id, Role = ChatMemberRole.Member });
chat.Members.Add(new ChatMember { UserId = bob.Id, Role = ChatMemberRole.Member });
scope.ServiceProvider.GetRequiredService<IChatRepository>().Add(chat);
var messages = scope.ServiceProvider.GetRequiredService<IMessageRepository>();
for (var i = 1; i <= 5; i++)
{
messages.Add(new Message { ChatId = chat.Id, SenderId = i % 2 == 0 ? alice.Id : bob.Id, Body = $"Message {i}" });
await Task.Delay(2); // a new millisecond, so the ids are in order
}
var saved = await scope.ServiceProvider.GetRequiredService<IUnitOfWork>().SaveChangesAsync();
Console.WriteLine($"Saved {saved} rows; chat created at {chat.CreatedAt:HH:mm:ss}");
}
await using (var scope = provider.CreateAsyncScope())
{
var alice = await scope.ServiceProvider.GetRequiredService<UserManager<User>>().FindByNameAsync("alice");
var chats = await scope.ServiceProvider.GetRequiredService<IChatRepository>()
.GetUserChatsAsync(alice!.Id, after: null, limit: 20);
foreach (var item in chats.Items)
{
Console.WriteLine($"Chat with {item.Peer?.UserName}: {item.UnreadCount} unread, last: {item.LastMessage?.Body}");
}
var history = scope.ServiceProvider.GetRequiredService<IMessageRepository>();
var page = await history.GetPageAsync(chats.Items[0].Chat.Id, before: null, after: null, limit: 2);
while (true)
{
Console.WriteLine($"Page: {string.Join(", ", page.Items.Select(m => m.Body))}");
if (page.NextCursor is null) break;
page = await history.GetPageAsync(chats.Items[0].Chat.Id, before: page.NextCursor, after: null, limit: 2);
}
}#:property PublishAot=false is needed because .NET 10 compiles file-based programs for Native AOT by default, and EF Core cannot build its model in that mode. Make sure the database runs (./Run.ps1 db in the repository), then:
powershell
dotnet run data.csCheck
Create alice: True
Create bob: True
Saved 8 rows; chat created at 20:18:42
Chat with bob: 3 unread, last: Message 5
Page: Message 5, Message 4
Page: Message 3, Message 2
Page: Message 1- 8 rows: the chat, two members and five messages, saved by one
SaveChangesAsync. Alice and Bob were saved earlier, byUserManager. - The chat got its
CreatedAt(your time differs) from the interceptor — the program never set it. - 3 unread for Alice: messages 1, 3 and 5 are Bob's, her own messages 2 and 4 do not count.
- The history comes back newest first in pages of two, and the last page has no next cursor.
The program creates users with fixed names, so a second run fails: Create alice: False (the name is taken), and then SaveChangesAsync throws a DbUpdateException, because the new chat refers to the id of an Alice that was never saved — a foreign key violation. Empty the tables before running it again; truncate … cascade also empties every table that refers to users:
powershell
docker compose exec postgres psql -U postgres -d chatex -c "truncate users cascade;"