Skip to content

Factory interface: Referencing Named Bindings

bartelink edited this page Feb 29, 2012 · 14 revisions

Factory interface: Referencing Named Bindings

In some cases when employing an Abstract Factory using the extension, one wants to use a specific Named Binding (i.e., where the Bind<T> expression terminates in a .Named("name") subexpression). The default instance provider of the extension used a convention of attempting to resolve an instance based on a named binding whenever the name of the method declaration on the abstract factory interface method starts with “Get”. For instance:-

IFoo GetMySpecialFoo()

leads to the internally generated code performing the equivalent of the following resolution call:

resolutionRoot.Get<IFoo>("MySpecialFoo");

Example customisation: Treating the first factory method parameter as a name specifier

If you wish to control the binding name based on a string in your code rather than this convention, this can be achieved by hooking in a [custom instance provider](Factory interface custom instance provider) implemented as follows:-

class UseFirstArgumentAsNameInstanceProvider : StandardInstanceProvider
{
    protected override string GetName(System.Reflection.MethodInfo methodInfo, object[] arguments)
    {
        return (string)arguments[0];
    }

    protected override Parameters.ConstructorArgument[] GetConstructorArguments(System.Reflection.MethodInfo methodInfo, object[] arguments)
    {
        return base.GetConstructorArguments(methodInfo, arguments).Skip(1).ToArray();
    }
}

this.Bind<IMyFactory>().ToFactory(() => new UseFirstArgumentAsNameInstanceProvider());

Clone this wiki locally