Search code examples
light-inject

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?


Solution

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