light-inject

Lightinject Equivalent of Ninject's WhenInjectedInto


Does LightInject have an equivalent method of Ninject's WhenInjectedInto()? (Ninject - Contextual Binding)

For example, I have two classes, let's say MicrosoftOffice and LibreOffice, that implement an interface IOfficeSuite. Two other classes, Windows and Linux, implement another interface, IOperatingSystem. The latter interface depends on IOfficeSuite.

I'd like to decide which office suite to instantiate based on the context. So if LightInject is injecting an IOfficeSuite implementation into a Windows object, it should choose MicrosoftOffice; if it is a Linux object, it should inject an LibreOffice instance.

Thanks


Solution

  • I was able to solve it using RegisterConstructorDependency:

    Container.RegisterConstructorDependency((factory, parameterInfo) => DecideImplementationByDeclaringType(factory, parameterInfo));
    
    private static IInterface DecideImplementationByDeclaringType(IServiceFactory factory, ParameterInfo parameterInfo)
        {
            var declaringType = parameterInfo.Member.DeclaringType;
    
            if (declaringType == typeof (SomeClass))
            {
                return factory.GetInstance<IInterface >("OtherImplementation");
            }
            return factory.GetInstance<IInterface >("DefaultImplementation");
        }