Skip to main content

Migrating old AutoMapper codes to 4.2 version with instance based approach

In AutoMapper 4.2 version, static implementation is removed with instance approach. It could be a nightmare to migrate the codes to the newer version with instance approach. I will be putting up guide for migrating codes from the older version to instance approach if someone has used Profile based approach.

Previous implementation (old implementation)

Profile based implementation mapping

 public class UserProfileMapping  
      : Profile  
 {  
      protected override void Configure()  
      {  
           Mapper.CreateMap<UserProfile, PreferenceViewModel>()  
             .ForMember(vm => vm.UserId, m => m.MapFrom(profile => profile.Id));  
      }  
 }  

Single class for registering all AutoMapper configuration

 public static class AutoMapperConfiguration  
 {  
      public static void Configure()  
      {  
           Mapper.Initialize(cfg =>  
           {  
                cfg.AddProfile(new UserProfileMapping());  
           });  
      }  
 }  

The global mapping initialization under global.asax

 AutoMapperConfiguration.Configure();  

Usage under controllers

 var dbUserProfile = // call for getting info from DB.  
 var preference = new PreferenceViewModel();  
 Mapper.Map(dbUserProfile, preference);  

Automapper Queryable Extensions implementation

 var dbQuery = // Db call  
 dbQuery.Project().To<PreferenceViewModel>()  


These above processes were old approach with static methods calls.
In the newer version, there has to be instance based approach, the biggest advantage is dependency injection. I am hoping the API would improve and with this new move someone can create a standard for Mapping the domain models and view models later.


AutoMapper new implementation based on instance approach

Let's start with the order that I followed with the older approach. I will be using constructor dependency injection to wire the whole process.

Profile based implementation mapping

 public class UserProfileMapping   
      : Profile  
 {    
      private readonly IMapperConfiguration MappingConfiguration;  
      public UserProfileMapping(IMapperConfiguration config)  
      {  
           MappingConfiguration = config;  
      }  
      protected override void Configure()  
      {  
           MappingConfiguration  
                .CreateMap<UserProfile, PreferenceViewModel>()  
                .ForMember(vm => vm.UserId, m => m.MapFrom(profile => profile.Id));  
      }  
 }  

The IMapperConfiguration is a new interface for mapping models which we would be checking at a later stage.

Single class for registering all AutoMapper configuration

 public class AutoMapperConfiguration  
 {  
      public AutoMapperConfiguration(IMapperConfiguration mapperConfiguration)  
      {  
           Configure(mapperConfiguration);  
      }  
      public void Configure(IMapperConfiguration mapperConfiguration)  
      {  
           mapperConfiguration.AddProfile(new UserProfileMapping(mapperConfiguration));  
      }  
 }  

If you check changes, the static declaration is removed from class and function both. Implementation is also changed based on dependency injection.


Dependency injection initialization through Ninject (The global mapping initialization under global.asax)

I am including possible mappings which may depend based on application. You can choose based on need.

 // AutoMapper mapping  
 kernel.Bind<MapperConfiguration>()  
       .ToSelf()  
       .InRequestScope()  
       .WithConstructorArgument<Action<IMapperConfiguration>>(  
             cfg => new AutoMapperConfiguration(cfg));  
 kernel.Bind<IConfigurationProvider>().ToMethod(ctx => ctx.Kernel.Get<MapperConfiguration>());  
 kernel.Bind<IMapper>().ToMethod(maper => kernel.Get<MapperConfiguration>().CreateMapper()).InSingletonScope();  
 kernel.Bind<IExpressionBuilder>().ToConstructor(ctx => new ExpressionBuilder(kernel.Get<MapperConfiguration>()));  

The MapperConfiguration has Action<IMapperConfiguration> type constructor parameter. In this, the anonymous action is created and IMapperConfiguration is created to be passed as a parameter for AutoMapperConfiguration .

The other key point is the creation of IMapper implementation instance through CreateMapper() method. This IMapper will be passed across all application to consume mappings.

IConfigurationProvider and IExpressionBuilder can be used for projecting LINQ queries to targetted mapped model.

Usage under controllers

In the controllers, the constructor parameters are taking care of instances  for mappers. Mainly, IMapper is used of mapping objects.

 public class AccountController  
      : Controller  
 {  
      private readonly IMapper Mapper;  
      public AccountController(IMapper modelMapper)  
      {  
           // Initialization codes  
      }  
      public ActionResult UserPreference()  
      {  
           var dbUserProfile = // call for getting info from DB.   
           var preference = new PreferenceViewModel();   
           Mapper.Map(dbUserProfile, preference);   
           // Code  
      }  
 }  


Automapper Queryable Extensions implementation

For extension method ideally, IExpressionBuilder needs to be used for LINQ projection but due to some issue or incompatibilty with QueryableExtensions, I am using IConfigurationProvider to do projection.

 public class AccountController  
      : Controller  
 {  
      private readonly IConfigurationProvider ConfigurationProvider;  
      public AccountController(IMapper modelMapper,  
           IConfigurationProvider configurationProvider)  
      {  
           // Initialization codes  
      }  
      public ActionResult UserPreference()  
      {  
           var dbQuery = // Db call   
           var res = dbQuery.ProjectTo<PreferenceViewModel>(ConfigurationProvider)   
           // Code  
      }  
 }  



Popular posts from this blog

Architecture solution composting Repository Pattern, Unit Of Work, Dependency Injection, Factory Pattern and others

Project architecture is like garden, we plant the things in certain order and eventually they grow in similar manner. If things are planted well then they will all look(work) great and easier to manage. If they grow as cumbersome it would difficult to maintain and with time more problems would be happening in maintenance.

There is no any fixed or known approach to decide project architecture and specially with Agile Methodology. In Agile Methodology, we cannot predict how our end products will look like similarly we cannot say a certain architecture will fit well for entire development lifespan for project. So, the best thing is to modify the architecture as per our application growth. I understand that it sounds good but will be far more problematic with actual development. If it is left as it is then more problems will arise with time. Just think about moving plant vs a full grown tree.

Coming to technical side, In this article, I will be explaining about the various techniques tha…

LDAP with ASP.Net Identity Core in MVC with project.json

Lightweight Directory Access Protocol (LDAP), the name itself explain it. An application protocol used over an IP network to access the distributed directory information service.

The first and foremost thing is to add references for consuming LDAP. This has to be done by adding reference from Global Assembly Cache (GAC) into project.json

"frameworks": { "net461": { "frameworkAssemblies": { "System.DirectoryServices": "4.0.0.0", "System.DirectoryServices.AccountManagement": "4.0.0.0" } } },
These System.DirectoryServices and System.DirectoryServices.AccountManagement references are used to consume LDAP functionality.

It is always better to have an abstraction for irrelevant items in consuming part. For an example, the application does not need to know about PrincipalContext or any other dependent items from those two references to make it extensible. So, we can begin with some bas…

Configuring Ninject, Asp.Net Identity UserManager, DataProtectorTokenProvider with Owin

It can be bit tricky to configure both Ninject and Asp.Net Identity UserManager if some value is expected from DI to configure UserManager. We will look into configuring both and also use OwinContext to get UserManager.

As usual, all configuration need to be done on Startup.cs. It is just a convention but can be used with different name, the important thing is to decorate class with following attribute to make it Owin start-up:

[assembly: OwinStartup(typeof(MyProject.Web.Startup))]
Ninject configuration

Configuring Ninject kernel through method which would be used to register under Owin.

Startup.cs
public IKernel CreateKernel() { var kernel = new StandardKernel(); try { //kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>(); // TODO: Put any other injection which are required. return kernel; } catch { kernel.Dispose(); throw; }…