Tomasz Plonka
Tomasz Plonka

Reputation: 305

How to pass a parameter to a named services in LightInject?

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?

Upvotes: 3

Views: 3001

Answers (1)

seesharper
seesharper

Reputation: 3379

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) { }        
}

Upvotes: 4

Related Questions