Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
June 16, 2021 08:24 pm GMT

Implement Chain of Responsibility/Commands in C Using ChainRunner

I have been working on an ASP.NET Core Web API application which is responsible for users' comments. This application needs to reject or censor new comments based on multiple business criteria. In simple words, each new comment must go through the following steps:

  • Censor curse words
  • Modify incorrect words
  • Reject if it has improper tone

The steps are not that complex and must be executed sequentially. To implement these steps, I decided to go for chain of responsibility pattern. However, I could not find a simple and proper library to implement this pattern so I created a library called ChainRunner to make all this work.

ChainRunner Schema

This picture depicts how ChainRunner works

Implementation

For each step I created a responsibility handler:

public class CensorCurseWordsHandler : IResponsibilityHandler<Comment>{    public Task HandleAsync(Comment request, CancellationToken cancellationToken = default)    {        // process comment ...    }}public class ModifyIncorrectWordsHandler : IResponsibilityHandler<Comment>{    public Task HandleAsync(Comment request, CancellationToken cancellationToken = default)    {        // process comment ...    }}public class ImproperToneHandler : IResponsibilityHandler<Comment>{    public Task HandleAsync(Comment request, CancellationToken cancellationToken = default)    {        // process comment ...    }}

Then, I configured the chain in startup:

services.AddChain<Comment>()        .WithHandler<CensorCurseWordsHandler>()        .WithHandler<ModifyIncorrectWordsHandler>()        .WithHandler<ImproperToneHandler>();

Finally, I injected the chain into my class and ran the chain like so:

[ApiController][Route("[controller]")]public class CommentController{    private readonly IChain<Comment> _chain;    public CommentController(IChain<Comment> chain)    {        _chain = chain;    }    [HttpPost]    public async Task<IActionResult> Post(Comment comment)    {        await _chain.RunAsync(comment);        return Ok();    }}

Links


Original Link: https://dev.to/litenova/implement-chain-of-responsibility-commands-in-c-using-chainrunner-2420

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To