Код IT
← Каталог

Паттерны проектирования — C# и .NET

Фрагмент из «Паттерны проектирования»: C# и .NET.

csharp projectencyclopedia7-06-proektirovanie-i-arhitektura-115 embed URL статья в энциклопедии
C# main.cs
// Регистрация с ключами
services.AddKeyedTransient<IPaymentStrategy, CardPaymentStrategy>("card");
services.AddKeyedTransient<IPaymentStrategy, SBPPaymentStrategy>("sbp");

// Использование
public class PaymentService
{
    private readonly IServiceProvider _sp;
    public PaymentService(IServiceProvider sp) => _sp = sp;

    public async Task ProcessPayment(string method, PaymentData Данные)
    {
        var strategy = _sp.GetRequiredKeyedService<IPaymentStrategy>(method);
        await strategy.ExecuteAsync(Данные);
    }
}
// Регистрация с ключами
services.AddKeyedTransient<IPaymentStrategy, CardPaymentStrategy>("card");
services.AddKeyedTransient<IPaymentStrategy, SBPPaymentStrategy>("sbp");

// Использование
public class PaymentService
{
    private readonly IServiceProvider _sp;
    public PaymentService(IServiceProvider sp) => _sp = sp;

    public async Task ProcessPayment(string method, PaymentData Данные)
    {
        var strategy = _sp.GetRequiredKeyedService<IPaymentStrategy>(method);
        await strategy.ExecuteAsync(Данные);
    }
}