English
Repository interfaces
Step 1. Why repositories
Why. The business layer could use ChatexDbContext directly: db.Messages.Where(...). Chatex puts a thin layer of repositories in between, and the business layer sees only their interfaces. The reasons:
- One place per query. "The 50 messages before this one, with sender profiles and attachments" is written once, in
MessageRepository, and every service that needs a page of history callsGetPageAsync. Without repositories, the sameInclude/Where/OrderBychain would be copied — and later fixed in one copy only. - Names that say what, not how.
chats.GetDirectAsync(alice, bob)reads as the business rule; the details — the direct key, the unique index, the filter on deleted chats — stay inside. - A clean boundary. Chatex.Core does not reference EF Core types at all: no
DbContext, noIQueryable, noInclude. The services in module 3 can only do what the interfaces offer, so a query can never sneak into a service and run once per item in a loop. - A seam for tests and for change. The interfaces describe exactly what the business layer needs from storage.
Repository and Unit of Work
Both patterns come from Martin Fowler's Patterns of Enterprise Application Architecture. A repository behaves like an in-memory collection of entities: add, remove, find. A Unit of Work collects the changes made during one business operation and commits them together. A DbContext already implements both, so some teams use it directly; Chatex adds the thin interfaces for the reasons above. Each repository method is a one-liner or a single query; there is no generic IRepository<T> with dozens of methods nobody needs.
Step 2. Result models
Why. Most repository methods return entities. Two kinds of results need types of their own:
- A page of a list returns the items and the cursor of the next page, or
nullon the last page; - A row of the chat list combines data from several tables: the chat, the user's role and mute flag, a preview of the last message, the number of unread messages and, for direct chats, the other person.
Do. Create the folder Models:
cs
namespace Chatex.Data.Models;
/// <summary>One page of a keyset-paginated list. <paramref name="NextCursor"/> is null on the last page.</summary>
public sealed record CursorPage<TItem, TCursor>(IReadOnlyList<TItem> Items, TCursor? NextCursor)
where TCursor : struct;CursorPage is a generic record: a class whose equality compares values, written in one line with a primary constructor. The constraint where TCursor : struct lets TCursor? mean Nullable<TCursor>, so a cursor of type Guid becomes Guid? — null meaning "no more pages".
cs
using Chatex.Data.Entities;
namespace Chatex.Data.Models;
/// <summary>A row of a user's chat list.</summary>
/// <param name="Peer">The other member of a direct chat; null for groups and channels.</param>
public sealed record ChatListItem(
Chat Chat,
ChatMemberRole Role,
bool IsMuted,
MessagePreview? LastMessage,
int UnreadCount,
UserSummary? Peer);
public sealed record MessagePreview(Guid Id, Guid SenderId, string Body, DateTimeOffset CreatedAt);
public sealed record UserSummary(Guid Id, string UserName, string DisplayName, string? AvatarPath);
/// <summary>Position in the chat list, which is ordered by (LastActivityAt, ChatId) descending.</summary>
public readonly record struct ChatListCursor(DateTimeOffset LastActivityAt, Guid ChatId);MessagePreview and UserSummary carry only what the chat list shows, not whole entities. ChatListCursor is a readonly record struct: a small value type with value equality, ideal for a cursor made of two values. Why two values is the subject of The chat list.
Step 3. The interfaces
Do. Create the folder Abstractions. The interfaces are public: Chatex.Core uses them. Read the comments — they are the contract of each method and say which results are tracked (changes to them are saved by the next SaveChangesAsync) and which are read-only, and which methods write immediately instead of waiting for SaveChangesAsync.
cs
using Chatex.Data.Entities;
namespace Chatex.Data.Abstractions;
/// <summary>
/// Users and their profiles. Creating users, passwords and email confirmation go through Identity's
/// <c>UserManager<User></c>, which uses the same DbContext.
/// </summary>
public interface IUserRepository
{
Task<User?> GetByIdAsync(Guid id, CancellationToken cancellationToken = default);
Task<User?> GetWithProfileAsync(Guid id, CancellationToken cancellationToken = default);
/// <summary>Case-insensitive substring search on user name and display name. Read-only results.</summary>
Task<IReadOnlyList<User>> SearchAsync(string query, int limit, CancellationToken cancellationToken = default);
/// <summary>The ids from <paramref name="ids"/> that belong to existing users.</summary>
Task<IReadOnlyList<Guid>> GetExistingIdsAsync(IReadOnlyCollection<Guid> ids, CancellationToken cancellationToken = default);
void AddProfile(UserProfile profile);
/// <summary>Writes immediately, without <see cref="IUnitOfWork.SaveChangesAsync"/>.</summary>
Task UpdateLastSeenAsync(Guid userId, DateTimeOffset lastSeenAt, CancellationToken cancellationToken = default);
}Users are created through Identity's UserManager<User> (topic 8), which hashes the password and checks the rules; the repository only reads users and adds profiles.
cs
using Chatex.Data.Entities;
namespace Chatex.Data.Abstractions;
public interface IRefreshTokenRepository
{
void Add(RefreshToken token);
/// <summary>Finds a token by its hash, with its user, tracked for revocation.</summary>
Task<RefreshToken?> GetByHashAsync(string tokenHash, CancellationToken cancellationToken = default);
/// <summary>Revokes every active token of the user (log out everywhere). Writes immediately; returns the count.</summary>
Task<int> RevokeAllForUserAsync(Guid userId, DateTimeOffset revokedAt, CancellationToken cancellationToken = default);
/// <summary>Deletes tokens that expired or were revoked before <paramref name="before"/>. Writes immediately.</summary>
Task<int> DeleteStaleAsync(DateTimeOffset before, CancellationToken cancellationToken = default);
}cs
using Chatex.Data.Entities;
using Chatex.Data.Models;
namespace Chatex.Data.Abstractions;
/// <summary>Direct chats, groups and channels. Soft-deleted chats are never returned.</summary>
public interface IChatRepository
{
/// <summary>Adds the chat; members added to <see cref="Chat.Members"/> are saved with it.</summary>
void Add(Chat chat);
Task<Chat?> GetByIdAsync(Guid id, CancellationToken cancellationToken = default);
Task<Chat?> GetDirectAsync(Guid userA, Guid userB, CancellationToken cancellationToken = default);
/// <summary>Handles are stored lower-case; the lookup lower-cases <paramref name="handle"/>.</summary>
Task<Chat?> GetByHandleAsync(string handle, CancellationToken cancellationToken = default);
/// <summary>Public groups and channels whose title or handle contains <paramref name="query"/>. Read-only results.</summary>
Task<IReadOnlyList<Chat>> SearchPublicAsync(string query, int limit, CancellationToken cancellationToken = default);
/// <summary>The user's chats, most recently active first, with last message, unread count and direct-chat peer.</summary>
Task<CursorPage<ChatListItem, ChatListCursor>> GetUserChatsAsync(
Guid userId, ChatListCursor? after, int limit, CancellationToken cancellationToken = default);
/// <summary>Moves <see cref="Chat.LastActivityAt"/> forward to <paramref name="at"/>. Writes immediately.</summary>
Task TouchAsync(Guid chatId, DateTimeOffset at, CancellationToken cancellationToken = default);
}cs
using Chatex.Data.Entities;
using Chatex.Data.Models;
namespace Chatex.Data.Abstractions;
public interface IChatMemberRepository
{
void Add(ChatMember member);
void Remove(ChatMember member);
Task<ChatMember?> GetAsync(Guid chatId, Guid userId, CancellationToken cancellationToken = default);
Task<bool> IsMemberAsync(Guid chatId, Guid userId, CancellationToken cancellationToken = default);
Task<int> CountAsync(Guid chatId, CancellationToken cancellationToken = default);
/// <summary>The users from <paramref name="userIds"/> who are already members of the chat.</summary>
Task<IReadOnlyList<Guid>> GetExistingUserIdsAsync(
Guid chatId, IReadOnlyCollection<Guid> userIds, CancellationToken cancellationToken = default);
/// <summary>Members ordered by user id, with user and profile. Pass the previous page's cursor as <paramref name="afterUserId"/>.</summary>
Task<CursorPage<ChatMember, Guid>> GetMembersAsync(
Guid chatId, Guid? afterUserId, int limit, CancellationToken cancellationToken = default);
/// <summary>Ids of the user's (not deleted) chats, e.g. to join SignalR groups on connect.</summary>
Task<IReadOnlyList<Guid>> GetChatIdsForUserAsync(Guid userId, CancellationToken cancellationToken = default);
/// <summary>
/// Moves the read position to <paramref name="messageId"/> if it is newer than the current one.
/// Writes immediately; returns false when nothing changed.
/// </summary>
Task<bool> MarkReadAsync(Guid chatId, Guid userId, Guid messageId, CancellationToken cancellationToken = default);
}cs
using Chatex.Data.Entities;
using Chatex.Data.Models;
namespace Chatex.Data.Abstractions;
public interface IMessageRepository
{
void Add(Message message);
/// <summary>Tracked, with attachments, for editing or deleting.</summary>
Task<Message?> GetByIdAsync(Guid id, CancellationToken cancellationToken = default);
/// <summary>Read-only, with sender profile and attachments, as history pages return it.</summary>
Task<Message?> GetDetailsAsync(Guid id, CancellationToken cancellationToken = default);
Task<bool> ExistsInChatAsync(Guid chatId, Guid messageId, CancellationToken cancellationToken = default);
/// <summary>
/// Keyset page of a chat's history, with sender profile and attachments. Read-only results.
/// <list type="bullet">
/// <item>Neither cursor: newest messages, newest first.</item>
/// <item><paramref name="before"/>: older messages, newest first (scrolling up).</item>
/// <item><paramref name="after"/>: newer messages, oldest first (filling the gap after a reconnect).</item>
/// </list>
/// <see cref="CursorPage{TItem,TCursor}.NextCursor"/> is the id to pass in the same direction for the next page.
/// </summary>
Task<CursorPage<Message, Guid>> GetPageAsync(
Guid chatId, Guid? before, Guid? after, int limit, CancellationToken cancellationToken = default);
}cs
using Chatex.Data.Entities;
namespace Chatex.Data.Abstractions;
public interface IAttachmentRepository
{
void Add(Attachment attachment);
void Remove(Attachment attachment);
/// <summary>Tracked, with its message (if any) to check access through the message's chat.</summary>
Task<Attachment?> GetByIdAsync(Guid id, CancellationToken cancellationToken = default);
/// <summary>The uploader's attachments from <paramref name="ids"/> not yet linked to a message. Tracked.</summary>
Task<IReadOnlyList<Attachment>> GetPendingAsync(
Guid uploaderId, IReadOnlyCollection<Guid> ids, CancellationToken cancellationToken = default);
/// <summary>Uploads never linked to a message and created before <paramref name="before"/>. Tracked.</summary>
Task<IReadOnlyList<Attachment>> GetStalePendingAsync(
DateTimeOffset before, int limit, CancellationToken cancellationToken = default);
}cs
namespace Chatex.Data.Abstractions;
/// <summary>
/// Stores uploaded files (attachments, avatars). Files are addressed by a storage path the storage picks itself,
/// e.g. <c>2026/11/{guid}</c>; client file names are never part of it.
/// </summary>
public interface IFileStorage
{
/// <summary>Writes <paramref name="content"/> to a new file and returns its storage path.</summary>
Task<string> SaveAsync(Stream content, CancellationToken cancellationToken = default);
/// <exception cref="FileNotFoundException">No file has this storage path.</exception>
Task<Stream> OpenReadAsync(string storagePath, CancellationToken cancellationToken = default);
/// <summary>Deletes the file; does nothing if it does not exist.</summary>
Task DeleteAsync(string storagePath, CancellationToken cancellationToken = default);
}Some conventions run through all of them:
AddandRemoveare synchronous. They only tell the context to track an object; nothing touches the database until the Unit of Work saves.- Every asynchronous method takes a
CancellationTokenwith a default value. When a browser closes the connection, ASP.NET Core cancels the token, and the query stops instead of finishing for nobody. The analyzers of topic 2 warn when a token is available but not passed on. - Collections are returned as
IReadOnlyList<T>, so a caller cannot add to a result list and believe it changes the database. Task<T?>with a nullable result means "may not exist": the caller must handlenull, and the compiler reminds it.
Check
dotnet build succeeds. The comment of IUserRepository.UpdateLastSeenAsync refers to IUnitOfWork, which does not exist yet; the compiler checks such references only when it generates documentation files, so the IDE may underline it until the next chapter.