Thursday, May 29, 2014

Inject parameters into unmapped Types using InjectionMap

InjectionMap lets you easily resolve mapped types and automatically injects the parameters into the constructor. This helps to resolve types that depend upon constructors that contain parameters.

In this example there there is a type named MappedTyp that has a constructor that accepts a type of ITypeArgument.
public interface ITypeArgument
{
}

public class TypeArgument : ITypeArgument
{
}

public interface IMappedType
{
}

public class MappedType : IMappedType
{
   public UnmappedType(ITypeArgument argument) { }
}

InjectionMap can resolve MappedType when both ITypeArgument and IMappedType are mapped into InjectionMap.
using (var mapper = new InjectionMapper())
{
   mapper.Map<ITypeArgument, TypeArgument>();
   mapper.Map<IMappedType, MappedType>();
}

using (var resolver = new InjectionResolver())
{
   var map = resolver.Resolve<IMappedType>();
}

This will automatically create a instance of MappedTyp and inject a resolved instance of ITypeArgument into the constructor.

Optionaly the parameter can be injected manually. Simply create an instance of UnmappedType and inject TypeArgument by resolving ITypeArgument with InjectionMap.
public interface ITypeArgument
{
}

public class TypeArgument : ITypeArgument
{
}

public class UnmappedType
{
   public UnmappedType(ITypeArgument argument) { }
}

using (var mapper = new InjectionMapper())
{
   mapper.Map<ITypeArgument, TypeArgument>();
}

using (var resolver = new InjectionResolver())
{
   var map = new UnmappedType(resolver.Resolve<ITypeArgument>());
}

Since the version 1.4.3 InjectionMap can also resolve unmapped types and inject the parameters based on the registered maps. Simply create a mapping of ITypeArgument and resolve UnmappedType without mapping it in InjectionMap. InjectionMap creates an instance of UnmappedType and injects TypeArgument by resolving ITypeArgument.

public interface ITypeArgument
{
}

public class TypeArgument : ITypeArgument
{
}

public class UnmappedType
{
   public UnmappedType(ITypeArgument argument) { }
}

using (var mapper = new InjectionMapper())
{
   mapper.Map<ITypeArgument, TypeArgument>();
}

using (var resolver = new InjectionResolver())
{
   var map = resolver.Resolve<UnmappedType>();
}

There is no need to create a new instance of UnmappedType or to register it to the InjectionMap. The Parameters will automatically be resolved and injected.

No comments: