WYSIWYG

http://kufli.blogspot.com
http://github.com/karthik20522

Thursday, March 15, 2012

Automapper setup in WCF

Unlike Asp.NET, WCF has no global.ascx file where we can instantiate global objects for the life of the AppPool or until IIS restarts. Most programmers at some time would have used Object mappers such as AutoMapper etc. Automapper by far is my favorite of object mappers, simple to use and easy to configure. But AutoMapper requires the object properties be mapped between Source type and Destination type before any mapping is executed. This can be fairly easily be achieved in Asp.net by creating the mapping in global.ascx thus automapper is ready to map objects when requests are made. But in WCF, since it’s stateless there is no global class that is executed once for the lifetime of the service. But there are other ways to go around this global execution.

One such way is to create a ServiceBehavior that is executed when the Service is initialized. Following is how it’s done:

Step 1, is to create ths ServiceBehavior which would bind to all services and calls’ the automapper initialization function



Note: following namespaces are required for the above code to work


Having the ServiceBehavior an Attribute type, we can pick and choose services to provide more control. And in the AutomapBootstrap class we define the mappers



Having a static function helps in not creating a new AutomapBootstrap object on every service request. This same technique can be used if you use ServiceLocators (IOC) which requires global initialization.

Labels: , ,