A day with .Net

My day to day experince in .net

Using AutoMapper with WCF

Posted by vivekcek on June 24, 2014

1. Create WCF application.

2. Through Nuget add AutoMapper.

3. Now we will create a bootstrap class to initialize automapper.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using AutoMapper;
using MoviesLibrary;

namespace DVDService
{
    public class AutomapBootstrap
    {
        public static void InitializeMap()
        {
            Mapper.CreateMap<Movie, MovieData>();
            Mapper.CreateMap<MovieData, Movie>();
            
        }
    }

}

4. To call this bootstrap when you call the service, we will create a service behavior attribute.

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.Web;

namespace DVDService
{
    public sealed class AutomapServiceBehavior : Attribute, IServiceBehavior
    {
        public AutomapServiceBehavior()
        {
        }


        public void AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase,
            Collection<ServiceEndpoint> endpoints, BindingParameterCollection bindingParameters)
        {
            AutomapBootstrap.InitializeMap();
        }

        public void ApplyDispatchBehavior(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
        {

        }

        public void Validate(ServiceDescription serviceDescription, System.ServiceModel.ServiceHostBase serviceHostBase)
        {

        }

        
    }

}

5. Now decorate your service with this attribute.

[AutomapServiceBehavior]
    [ServiceErrorBehavior(typeof(ElmahErrorHandler))]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class DVDService : IDVDService
    {
        MovieDataSource dataSource = null;

        public List<Movie> GetAllData()
        {
            try
            {
                List<MovieData> movies = dataSource.GetAllData();
                List<Movie> mappedMovies = Mapper.Map<List<MovieData>, List<Movie>>(movies);
                return mappedMovies;
            }
            catch (Exception ex)
            {
                throw new FaultException(ex.Message);
            }
        }
Advertisements

One Response to “Using AutoMapper with WCF”

  1. grahamtoms said

    Thanks! Great example.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s