How do I pass a parameter to the constructor using Light Inject?

前端 未结 4 1094
忘了有多久
忘了有多久 2021-01-01 11:41

Does Light Inject 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 DependencyOve

4条回答
  •  攒了一身酷
    2021-01-01 12:11

    The above will all work if your constructor does not have any other dependencies (or you want to resolve these dependencies manually). If you have the scenario below though it falls down:

    public class Test : ITest
    {
       private IFoo _foo;
       public Test(string parameter, IFoo foo)
       {
          _foo = foo;
          ....
       }
    }
    

    Now you not only have to manually inject the string but also Foo. So now your not using dependancy injection at all (really). Also Simple Injector state:

    Simple Injector does not allow injecting primitive types (such as integers and string) into constructors.

    My reading of this is that they're saying "don't do this".

    Extensibillity points

    Another option here is to use "Extensibillity points" for this scenario.

    To do this you need to abstract your hard coded elements from your injected elements:

    public class Test : ITest
    {
       private IFoo _foo;
       public Test(IFoo foo)
       {
          _foo = foo;
          ....
       }
    
      public void Init(string parameter)
      {
    
      }
    }
    

    You can now inject your dependanices and your hardcoded elements:

    _container.Register();
    _container.RegisterInitializer(instance => {instance.Init("MyValue");});
    

    If you now add another dependancy, your injection will now work without you having to update the config, i.e. your code is nicely de-coupled still:

    public class Test : ITest
    {
       private IFoo _foo;
       private IBar _bar;
       public Test(IFoo foo, IBar bar)
       {
          _foo = foo;
          _bar = bar;
          ....
       }
    
      public void Init(string parameter)
      {
    
      }
    }
    

提交回复
热议问题