English
Registering the business layer
Step 1. One call for everything below the API
Why. In topic 5 the data layer got AddData. The business layer gets its own AddCore, and AddCore calls AddData itself. The API (topic 12) will then call only AddCore: it does not need to know that the business layer stores its data with EF Core, nor which connection string and storage folder the data layer needs.
AddCore receives the application's configuration — the merged settings of appsettings.json, appsettings.Development.json, environment variables and command-line arguments — and reads what the layers below need from it.
Do. Create DependencyInjection.cs in the root of Chatex.Core:
cs
using Chatex.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
namespace Chatex.Core;
public static class DependencyInjection
{
public static IServiceCollection AddCore(this IServiceCollection services, IConfiguration configuration)
{
var connectionString = configuration.GetConnectionString("Chatex")
?? throw new InvalidOperationException("Connection string 'Chatex' is not configured.");
services.AddData(connectionString, o => o.RootPath = configuration["Storage:RootPath"] ?? "");
return services;
}
}configuration.GetConnectionString("Chatex")readsConnectionStrings:Chatex. A missing connection string is a deployment mistake, not an expected failure, so it throws at start-up with a clear message.??with athrowexpression is the shortest way to say "this or fail".configuration["Storage:RootPath"]reads a nested setting;:separates the levels of the JSON sections.
The class grows with every topic of this module: each feature registers its services here. In topic 8 it also gets the first options class (JwtOptions), bound from a configuration section and validated at start-up — the same pattern as FileStorageOptions in the data layer.
Constructor injection
None of the services we are going to write creates its own dependencies. ChatService, for example, declares in its primary constructor that it needs IChatRepository, IUnitOfWork, IChatNotifier, TimeProvider and others, and the container passes them in. This is constructor injection: the dependencies are visible in the signature, a test can supply other implementations, and the service depends on interfaces (IChatRepository), not on classes (ChatRepository). The C# course explains the container in Dependency injection.
Step 2. Try the Result type
Why. There is no service yet to test, but the Result type is complete. A small program shows how it feels to use — the implicit conversions, IsSuccess, Match and the exception for a misused Value.
Do. In your playground folder (D:\Work\Playground), create results.cs; fix the path in the first line if your repository is elsewhere:
cs
#:project D:\Work\Chatex\Source\Chatex.Core\Chatex.Core.csproj
#:property PublishAot=false
using Chatex.Core.Common;
Result<decimal> Withdraw(decimal balance, decimal amount)
{
if (amount <= 0)
{
return Error.Validation("amount", "invalid_amount", "The amount must be positive.");
}
if (amount > balance)
{
return Error.Conflict("insufficient_funds", "Not enough money on the account.");
}
return balance - amount;
}
foreach (var amount in new[] { 30m, 0m, 500m })
{
var result = Withdraw(100m, amount);
var text = result.Match(
rest => $"OK, {rest} left",
error => $"{error.Kind} {error.Code}: {error.Message}");
Console.WriteLine($"Withdraw {amount}: {text}");
}
var failed = Withdraw(100m, 500m);
if (!failed.IsSuccess)
{
Console.WriteLine($"The compiler knows Error is not null here: {failed.Error.Code}");
}
try
{
Console.WriteLine(failed.Value);
}
catch (InvalidOperationException ex)
{
Console.WriteLine($"Reading Value of a failure is a bug: {ex.Message}");
}The function Withdraw returns a Result<decimal>, yet its return statements return an Error or a decimal — the implicit conversions wrap them.
powershell
dotnet run results.csCheck
Withdraw 30: OK, 70 left
Withdraw 0: Validation invalid_amount: The amount must be positive.
Withdraw 500: Conflict insufficient_funds: Not enough money on the account.
The compiler knows Error is not null here: insufficient_funds
Reading Value of a failure is a bug: Result has no value; it failed with 'insufficient_funds'.Hover over failed.Error.Code in the IDE: there is no nullable warning, thanks to [MemberNotNullWhen]. Remove the if around it and the warning appears.