Search code examples
inversion-of-controlsimple-injector

How do I pass a parameter to the constructor using Simple Injector?


Does Simple Injector allow you to pass parameters to constructor when you resolve? I'd like to know if both these frameworks do what Unity's ResolverOverride or DependencyOverride both do.


Solution

  • I suspect that this question is about passing primitive values to the constructor at the time the service is actually resolved.

    Let's set up a simple test class:

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

    The Foo class takes a string argument that we would like to supply when resolving the IFoo service.

    var container = new ServiceContainer();
    container.Register<string, IFoo>((factory, value) => new Foo(value));
    var firstFoo = container.GetInstance<string, IFoo>("SomeValue");
    var secondFoo = container.GetInstance<string, IFoo>("AnotherValue");
    

    If we want to be able to create new instances of the Foo class without using the container directly, we can simply inject a function delegate.

    public interface IBar { }
    
    public class Bar : IBar
    {
        public Bar(Func<string, IFoo> fooFactory)
        {
            var firstFoo = fooFactory("SomeValue");
            var secondFoo = fooFactory("AnotherValue");
        }
    }
    

    The "composition root" now looks like this:

    var container = new ServiceContainer();
    container.Register<string, IFoo>((factory, value) => new Foo(value));
    container.Register<IBar, Bar>();
    var bar = container.GetInstance<IBar>();
    

    If the question is about passing a "static" primitive value to the contructor, this is simply done by registering a factory delegate like this.

    var container = new ServiceContainer();
    container.Register<IFoo>((factory) => new Foo("SomeValue"));
    var firstInstance = container.GetInstance<IFoo>();
    var secondInstance = container.GetInstance<IFoo>();
    

    The difference is that this approach does not let you pass a value at resolve time. The value is statically specified at registration time.