tags:

views:

386

answers:

0

Suppose I have this:

   public class CustomerViewModel
   {
      public CustomerViewModel(ICountryRepository countryRepository)
      {
      }
   }

   public class AddressViewModel
   {
      public AddressViewModel(ICountryRepository countryRepository)
      {
      }
   }

Now, I want to map it:

     AutoMapper.Mapper.CreateMap<Address, AddressViewModel>();
     AutoMapper.Mapper.CreateMap<Customer, CustomerViewModel>()
        .ForMember(x => x.Address, m => m.MapFrom(a => a.Addresses.FirstOrDefault()));

But obviously AutoMapper doesn't know about my DI container and how to instantiate these view models. How do I tell AutoMapper to use ServiceLocator.Current.GetInstance() - either globally or for this particular mapping?

I can use

        .ForMember(x => x.Address, m => m.MapFrom(a => 
           ServiceLocator.Current.GetInstance<AddressViewModel>().Setup(a.Addresses.FirstOrDefault())));

to do conversion manually... but this is not auto-mapping ;-)

Hm, in latest AutoMapper release there's

 .ConstructUsing(x => ServiceLocator.Current.GetInstance<CustomerViewModel>())

but as far as I see I'll have to do this for each mapping which is waste of typing work. Is there any way to setup it globally?

Also, I tried to do

      public CustomerViewModel(ICountryRepository countryRepository)
      {
             Address = new AddressViewModel(countryRepository);
      }

but AutoMapper still complains it cannot create AddressViewModel for Address, though Address is already created - there's no need to create it.

Update: well, I can use "m.UseDestinationValue();" but once again I want to do it globally. So here's another question: How can I setup global "mapping" actions? I.e. .UseDestinationValue(); for ALL mappings, etc.

related questions