In last two parts, we implemented Command and Abstract factory patterns. Let’s recapitulate task specification and class diagram.

Previous parts

Task recapitulation

Create REST API in C# that would receive JSON message with parameters method and data (message example is below this block). Parameter method represents statistical function as average (avg), variance (var) or standard deviation (std). API applies the selected method to the second parameter data (array of numbers).

{
"method": "avg",
"data": [1.0, 2.7, 5.4, 3.3, 9.1]
}
Class diagram

PostModel

Our controller will receive JSON data as a part of a POST request. ASP .NET Core controller is able to transform these data into a defined class structure. In our case, we will implement a simple model for the controller. Create class in path StatProjectAPI/Models/SimpleCommand/PostModel.cs

SimpleCommandController

StatProjectAPI/Controllers/SimpleCommandController.cs

As I mentioned before, the controller has to process the POST request. We will use dependency injection in order to obtain implemented abstract factory. Method SimpleCalculation obtains request JSON data as a model parameter. Look at line 30. in which is Command class created. Then (on line 33) is called Compute method of command.

Program

Now, we have created a controller! However, we have to create our abstract factory and fill it with Command classes. We have to register our abstract factory as a new service in the Program.cs . After registration, the abstract factory will replace the interface in the controller.

Let’s register our factory via the method AddSingleton. A concrete abstract factory is implemented in the lambda function. On lines 4–6, Command classes are registered into the abstract factory. So, we finally implement concrete classes (in Program.cs)!

Commented line 10 is the registration of the first abstract factory (with dependencies).

Conclusion

Now, we are done! You can debug your solution via swagger and try to send a POST request. I hope, you learnt something about mentioned design patterns and enjoyed this tutorial.

You can find the complete sollution on my GitHub https://github.com/marrekb/Csharp_examples/tree/main/StatProject.

Thank you for your attention and good luck!

--

--

Marek Balaz

C# software developer and fan of programming techniques