1

Is it possible in LightInject IoC to resolve a type based on some custom method?

eg the resolver would call a method like this

public interface IMyType {}
public class MyEvenType : IMyType {}
public class MyOddType : IMyType {}
public static int Foo;    

public static IMyType ResolveType()
{
   if (Foo % 2 == 0)
       return MyEvenType;
   return MyOddType;
}

How would I write the container.Register method so that it calls the above method in order to resolve the dependency?

JK.
  • 21,477
  • 35
  • 135
  • 214

1 Answers1

2

LightInject allows you to register specific methods as factory resolver methods that will allow you to construct your type when you resolve the interface.

public class MyTypeResolver
{
    public static int Foo;    
    public static IMyType ResolveType()
    {
        if (Foo % 2 == 0)
            return new MyEvenType();
        return new MyOddType();
    }
}

When registering your interface, instead of registering to a concrete type, register to a factory method that returns a concrete type.

void Main()
{
    var container = new LightInject.ServiceContainer();
    container.Register<IMyType>(factory => MyTypeResolver.ResolveType());

    var instance1 = container.GetInstance<IMyType>();
    instance1.Dump();

    MyTypeResolver.Foo = 1;

    var instance2 = container.GetInstance<IMyType>();
    instance2.Dump();
}

instance1 has a concrete type of MyEvenType and instance2 has a concrete type of MyOddType.

David L
  • 32,885
  • 8
  • 62
  • 93
  • Thanks that might work. I see you have returned an instance of the type from the resolver: `return new MyEvenType();`. Is that instance what gets injected when the dependency is resolved? – JK. May 16 '15 at 04:31
  • @JK. It is. If you changed up the test to instead inject a static int and outputted that static int in each constructor, incrementing it between resolves, you'd see that it continues to increment (meaning that it resolves that respective instance of return new MyEvenType(), etc). – David L May 16 '15 at 04:43