Blazor Server Template - MediatR

2022. 5. 11. 00:00ASPNET/BlazorServerTemplate

반응형

MediatR 추가


개발자 프롬프트에서 프로젝트 폴더로 이동 
(현재 .sln 파일이 있는 폴더라면 .csproj 파일이 있는 폴더로 이동)
 
아래 명령 실행
 
dotnet add package MediatR.Extensions.Microsoft.DependencyInjection

 

 

Program.cs 에 다음 코드 추가
 

using MediatR;
using WebApiBasicTutorial.Helper;
...
builder.Services.AddMediatR(AssemblyHelper.GetAllAssemblies().ToArray());

 

Handler 폴더 추가

Handler/AddCount.cs 파일 추가

using MediatR;

namespace BlazorWebApp.Handler;

public class AddCount {

    public class Command : IRequest<Response>
    {
        public int CurrentValue { get; set; } 
        public int AddValue { get; set; }
    }
    public class Response 
    {
        public int CurrentValue { get; set; }
    }

    public class CounterHandler : IRequestHandler<Command, Response>
    {
        public async Task<Response> Handle(Command request, CancellationToken cancellationToken)
        {
            request.CurrentValue += request.AddValue;
            return await Task.FromResult(new Response() { CurrentValue =  request.CurrentValue });
        }
    }
}

Pages/CounterWithMediator.razor 파일 추가

@page "/counter/mediator"
@using BlazorWebApp.Logger
@using MediatR
@inject ILogger<Counter> logger
@inject IMediator  mediator

<PageTitle>Counter</PageTitle>

<h1>Counter</h1>

<p role="status">Current count: @currentCount</p>

<button class="btn btn-primary" @onclick="IncrementCount">Click me</button>

@code {
    private int currentCount = 0;

    private async Task IncrementCount()
    {
        var response = await mediator.Send(new Handler.AddCount.Command
        {
            AddValue = 1, 
            CurrentValue = currentCount 
        });
        currentCount = response.CurrentValue;
        logger.LogInformation($"currentCount = {currentCount}");
    }
}

 

실행

 

 

관련영상

https://youtu.be/V0eSagahtSc

 

 

반응형