DEV Community

Anand Mukundan
Anand Mukundan

Posted on • Originally published at dotnetindia.com on

Building for Alexa - 3 - Structuring your Code

In this post I want to discuss the way I like to structure my code when developing the Skill handling backend. As mentioned in previous posts, the handler is based on the ASP.NET WebAPI project template, which is based on MVC. So out of the box the structure is like below:

imageI like to structure the Intent Handling code in a way that I think makes it more maintainable and easier to debug. Again this is just my personal approach and is not in any way dictated by MVC or other patterns.

The AlexaSKillKit.net GitHub page has a get started section that would get you to the above structure and a working Skill handling backend.

So if you follow this structure you will have a basic Speechlet class that handles all of your intents and returns a SpeechletResponse to the Controller. The Controller is very light weight and just contains code to receive a POST and returning, what your Speechlet implementation returns, after converting it to a API response(HTTPResponseMessage).

Since all the intents land up in the single speechlet implementation class, I prefer to create separate handlers for each intent. I usually declare a IHandler interface that contains something a single method like below:

public virtual SpeechletResponse handleIntent(IntentRequest request, Session session, 
Context context, Dictionary<string, string> options=null)
Enter fullscreen mode Exit fullscreen mode

So for each category of intents (not always each intent, but in a lot of cases it ends up being that), there is a handler. The Speechlet implementation then hands off to the handler based on the intent received.

So our structure changes to something like this:

imageThis has some advantages. Since handler logic is separated out, it is easier to maintain and debug this code, instead of everything being in a big class. Also when later you want to do something like IOC, this structure will help make that possible.

I also prefer to have a set of service gateway classes that links up our handlers to the actual business services your may end up calling. These could be SOAP or REST based on your business, but most skills end up calling some kind of business services. So having a gateway pattern implementation would make future expansion and management of these interfaces easier.

Top comments (0)