Using Akka.NET with ASP.NET Core – Creating a Quiz API

This is a template and quick start guide for Akka.NET with ASP.NET Core. You can grab the concepts of using Akka.NET with ASP.NET Core and how Akka.NET actor model can be used in a simple quiz or survey based scenario.

But at the same time, this post will not provide all the fundamentals of actor model programming or Akka.NET. It assumes that you already have the understanding of the actor model and reactive programming basics, along with the some practical experience with the concepts of Akka.NET.

Scenario :  A quiz engine has many quizzes and users can attend the quizzes. Each user can attend many quizzes as possible at the same time. So each user session is associated with a quiz. One user can have many quiz sessions at the same time. A simplest session key is a combination of quiz Id and user Id. This combination is unique and referred as a session Id. Each session is an actor.

Also a template actor provides the quiz templates during the session creation. Each session actor gets the fresh copy of the quiz during session creation.

The below diagram shows the actor system used in this scenario.

Akka.NET actor model for quiz engine

Step by step explanation

  • In the ASP.NET Core Startup class the actor system (QuizActorSystem) is instantiated.
  • QuizMasterActor is created in the context of QuizActorSystem and the QuizActorSystem is added to the ASP.NET Core services collection, to be consumed by the controllers.
  • QuizMasterActor creates QuizSessionCoordinatorActor and QuizTemplateActor under its context.
  • For simplicity the QuizController of ASP.NET Core has two actions.
    1. GetQuestion – This gets session Id and question Id. The controller asks for the session actor from QuizSessionCoordinatorActor. If the session actor is already available it will be returned else QuizSessionCoordinatorActor will create a new session actor under its context. QuizSessionActor loads the quiz from the QuizTemplateActor in the initial creation, gets the fresh copy of the quiz and returns the requested question. Consequent requests will be served directly by the QuizSessionActor.
    2. GetAnswer – This action methods takes the session Id and the answer for the question and pass it to the right QuizSessionActor for the update.

The entire QuizSessionActor tree is created upon the request for a question under a specific session and this is quite safe and straight forward.

You can download the source code from this Github repo.

Advertisement