Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use AutoMApper.5.2.0 With Ninject?

I'm working on a large ASP.NET MVC 5 project nowadays and I'm implementing DI by using Ninject framework for MVC. Actually it's the first time to me to use Ninject and I'm in dire need to know what is the best practice of using AutoMApper 5.2.0 With it.

After Googling I found some examples which demonstrate an old version of AutoMapper that have some deprecated methods in the new version.

My solution is consist of the following projects:

  1. Core
  2. Data
  3. Service
  4. Web

I'm working on the same project in this link.

like image 683
Morz Avatar asked Mar 10 '23 12:03

Morz


1 Answers

there are three things you need to set up for AutoMapper in Ninject.

  1. Bind() AutoMapper.IMapper
  2. instruct AutoMapper to use Ninject for its services, and
  3. initialize AutoMapper with your mappings.

here is the NinjectModule I use for this purpose:

public class AutoMapperModule : NinjectModule
{
    public override void Load()
    {
        Bind<IMapper>().ToMethod(AutoMapper).InSingletonScope();
    }

    private IMapper AutoMapper(Ninject.Activation.IContext context)
    {
        Mapper.Initialize(config =>
        {
            config.ConstructServicesUsing(type => context.Kernel.Get(type));

            config.CreateMap<MySource, MyDest>();
            // .... other mappings, Profiles, etc.              

        });

        Mapper.AssertConfigurationIsValid(); // optional
        return Mapper.Instance;
    }
}

then you will just inject AutoMapper.IMapper into your classes instead of using the static Mapper

like image 162
Dave Thieben Avatar answered May 01 '23 17:05

Dave Thieben