Tuesday, September 2, 2014

InjectionMap.Configuration: Extension for InjectionMap

InjectionMap.Configuration is a small extension to InjectionMap that allows to register the mappings in the application configuration file.


Some simple types to demonstrate the mapping:
public interface IKeyOne { }
public class ObjectTypeOne : IKeyOne { }

public class InjectionMapInitializer : IMapInitializer
{
    public void InitializeMap(IMappingProvider container)
    {
        container.Map<IKeyThree, ObjectTypeThree>();
    }
}

Define the mappings in the config file.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <!-- Define the section -->
    <section name="injectionMap" type="InjectionMap.Configuration.InjectionMapSection, InjectionMap.Configuration" />
  </configSections>

  <injectionMap>
    <mappings>
      <!-- Register Map IKeyOne to ObjectTypeOne -->
      <map key="TestApp.IKeyOne, TestApp" for="TestApp.ObjectTypeOne, TestApp"/>
      <!-- Register Map ObjectTypeOne to self -->
      <map key="TestApp.ObjectTypeOne, TestApp" toSelf="true"/>
    </mappings>
    <initializers>
      <!-- Register MapInitializers -->
      <init type="TestApp.InjectionMapInitializer, TestApp"/>
    </initializers>
  </injectionMap>
</configuration>
</pre>

The Section has to be called "injectionMap" for InjectionMap to find it.
Import the namespace InjectionMap.Configuration and create a instance of InjectionMapper. To initialize the configuration just call the extensionmethod Initialize() on InjectionMapper. This call should only be made once per AppDomain, ideally in the application startup.

using InjectionMap.Configuration;
...

using (var mapper = new InjectionMapper())
{
    mapper.Initialize();
}

InjectionMap.Configuration can be downloaded from NuGet
PM > Install-Package InjectionMap.Configuration

The sourcecode is on Github

No comments: