This project is read-only.

Contextual Binding

It depends ... on the context in the case of a DI container. NInject has a feature called Contextual Binding that allows you to define when the container should inject which implementation.

After some experiments with Unity's type mapping system I can report that Unity also has this feature.

TecX offers some extension methods for IUnityContainer that allow you to define predicates to check for the appropriate conditions:

public static IUnityContainer RegisterType(this IUnityContainer container, Type @from, Type to,
    LifetimeManager lifetime, Predicate<IRequest> predicate, params InjectionMember[] InjectionMembers)

public static IUnityContainer RegisterInstance(this IUnityContainer container, Type @from, object instance,
    LifetimeManager lifetime, Predicate<IRequest> predicate)

Or if you prefer the fluent API of TecX' ConfigurationBuilder

var builder = new ConfigurationBuilder();
builder.For<IFoo>().Use( => /* do your magic here */ return true);

IRequest allows you to inspect the current build tree (i.e. all the objects Unity created during the current call to Resolve()) or arbitrary stuff you decide to put into its dictionary.

The code can be found in the TecX.Unity project (folder ContextualBinding).

Last edited Jul 16, 2012 at 4:42 PM by weberse, version 2


No comments yet.