Wednesday, 25 March 2015

ASP.NET Tips #31 - New Database Access Method in Web API

Most examples of Web API use either Entity Framework directly or show some abstractions such as Repository and/or UnitOfWork, which introduce a number of classes, as well as strong typing.

That's all good. However, in many Web API cases you're simply exposing, and possibly transforming, data from a data store. You are probably reading in values from a query string, JSON, or XML, and manipulating SQL.

All of these are strings. While you can certainly use a serializer to work with inputs and use casting to correctly validate data types, in many cases you can forego the cost of boxing/unboxing or serializing/deserializing by using dynamics.

I have a gist that shows how to do this using Dapper (with Async support):

https://gist.github.com/panesofglass/5212462

Use it as a way of eking out extra performance, rather than a standard approach.

Web API Tracing

Web API integrates tracing, so as to make it very easy to know what's going on throughout the lifetime of your services. Microsoft has released an addon package to enable tracing of Web API using System.Diagnostics. You can also find adapters for NLog and log4net on NuGet.

This is really helpful for tracking down unexpected responses or unhandled exceptions, especially in production applications. For the best performance, of course, you should use Event Tracing for Windows (ETW).

No comments :

Post a comment