3

In LightInject,registering a named service goes a s follows:

container.Register<IFoo, Foo>();
container.Register<IFoo, AnotherFoo>("AnotherFoo");
var instance = container.GetInstance<IFoo>("AnotherFoo");

A service with a parameter:

container.Register<int, IFoo>((factory, value) => new Foo(value));
var fooFactory = container.GetInstance<Func<int, IFoo>>();
var foo = (Foo)fooFactory(42); 

How to combine these two together, to have a named service with a parameter passed to a constructor?

Tomasz Plonka
  • 285
  • 4
  • 12
  • Could you come up with a simple example of what you are trying to do? – seesharper Jan 20 '15 at 07:32
  • I have a few classes that implement an interface. All of them have a constructor with a string parameter. So I try to get an object based on a name ("AnotherFoo", "OneMoreFoo") to call a method from the interface, supplying a parameter in ResolveNamed(..) – Tomasz Plonka Jan 20 '15 at 11:32

1 Answers1

4

You mean like this?

class Program
{
    static void Main(string[] args)
    {
        var container = new ServiceContainer();
        container.Register<string,IFoo>((factory, s) => new Foo(s), "Foo");
        container.Register<string, IFoo>((factory, s) => new AnotherFoo(s), "AnotherFoo");

        var foo = container.GetInstance<string, IFoo>("SomeValue", "Foo");
        Debug.Assert(foo.GetType().IsAssignableFrom(typeof(Foo)));

        var anotherFoo = container.GetInstance<string, IFoo>("SomeValue", "AnotherFoo");
        Debug.Assert(anotherFoo.GetType().IsAssignableFrom(typeof(AnotherFoo)));
    }
}


public interface IFoo { }

public class Foo : IFoo
{
    public Foo(string value){}        
}

public class AnotherFoo : IFoo
{
    public AnotherFoo(string value) { }        
}
seesharper
  • 3,249
  • 1
  • 19
  • 23