Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

N-Teir Architecture with ASP.NET Web API

I'm just trying to wrap my head around this concept. I have written a couple different Web APIs but they have always been consumed by a website and interacted via JSON. I have a question about how to structure the implementation when the Web API will be consumed by a windows service.

In this case there is already an existing Database so I want to use Entity Framework's Database First approach.

I create a Class Library project for the models and use Entity Framework to look at the existing database and generate all of the required classes.

Then I create a Web API Project and add my Class Library with all of the models to it. Up to this point I am good.

My question is when I go to build the Windows Service that will interact with the Web API, how do I access the classes from my Class Library model project? I know I could add that project to my windows service but that doesn't seem like the correct approach because that would pretty much by-pass the Web API.

I guess my question is if I want to create and pass an Employee object to my Web API (so it can insert it into the database) from my windows Service, how does the windows service get the Employee object without adding the Class Library to the Windows service project?

like image 671
jkruer01 Avatar asked Feb 18 '13 13:02

jkruer01


1 Answers

In an n-tier solution you don't pass domain objects across physical boundaries, but you implement data-transfer objects (DTO) that will only hold the required info by the consumer/caller.

Usually you're going to created a shared library that will have the whole data-transfer objects and this will be referenced both by the server and the client.

After that, it's all about using a JSON serializer in order to serialize and/or deserialize your data-transfer objects.

Domain objects will be always mapped to data-transfer objects because these are lighter than a full object. Make yourself a question: if the consumer only requires the name and the second name of someone, why you need to send more data over the wire?

In addition, it's important to avoid server dependencies in client applications and services.

Some useful tips:

  • Learn what's a DTO: http://en.wikipedia.org/wiki/Data_transfer_object and http://martinfowler.com/eaaCatalog/dataTransferObject.html

  • Check AutoMapper and how can save you time in order to map domain objects to data-transfer objects: http://automapper.org/

like image 161
Matías Fidemraizer Avatar answered Nov 13 '22 02:11

Matías Fidemraizer