An Interest In:
Web News this Week
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
- March 26, 2024
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.
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
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To