[HOW TO] Automapper MEF Injection IoC

Déclarer le "mapper engine" d'automapper avec MEF pour la résolution IoC.

1) Création du container MEF et déclaration IoC des interfaces :

  1.  
  2. private CompositionContainer container;
  3.  
  4. protected override void Configure()
  5. {
  6.     // Create MEF Container
  7.     var catalog =
  8.         new AggregateCatalog(
  9.             AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType<ComposablePartCatalog>());
  10.     container = new CompositionContainer(catalog);
  11.  
  12.     var batch = new CompositionBatch();
  13.  
  14.     // IoC Interfaces Registering
  15.     batch.AddExportedValue<IMyInterface>(new MyImplementation1());
  16.     batch.AddExportedValue<IMyInterface2>(new MyImplementation2());
  17.     // ...
  18.  
  19.     // Automapper configuration
  20.     ConfigurationStore configurationStore = new ConfigurationStore(new TypeMapFactory(), MapperRegistry.AllMappers());
  21.     batch.AddExportedValue<IConfiguration>(configurationStore);
  22.     batch.AddExportedValue<IConfigurationProvider>(configurationStore);
  23.     batch.AddExportedValue<IMappingEngine>(new MappingEngine(configurationStore));
  24.     batch.AddExportedValue(container);
  25.  
  26.     container.Compose(batch);
  27. }
  28.  

2) Import IoC via constructeur du controlleur / viewmodel ...etc

  1.         [ImportingConstructor]
  2.         MyViewModel(IService<Foo> fooService, ... , IMappingEngine mapper)
  3.         {
  4.             _fooService = fooService;
  5.             // .. other services
  6.             _mapper = mapper;
  7.         }


3) Utilisation du mapper :

  1.  
  2. FooDto myfooDtoInstance = _mapper.Map<Foo, FooDto>(myfooInstance);
  3.  

Lien pour la configuration IoC d'Automapper avec Unity :
http://blog.aspnet.sk/michalkohut/archive/2011/09/10/konfigur-225-cia-automapper-a-s-ioc.aspx

0 commentaires:

Enregistrer un commentaire