Morz
Morz

Reputation: 55

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.

Upvotes: 4

Views: 5699

Answers (1)

Dave Thieben
Dave Thieben

Reputation: 5437

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

Upvotes: 8

Related Questions