Passing parameter to ctor while having other parameters auto-resolved?
See original GitHub issueHi,
I have a (potentially strange) requirement in which I’d really like to be able to use the container to create a class that contains multiple ctor parameters while auto-resolving all parameters except also allow for specifying the value of potentially one or more at resolution time.
As an example let’s say I have this class structure and I want to be able to specify the string value when I resolve IFoo, but I would like IBar1 and IBar2 to be auto-resolved:
public interface IFoo
{
}
public interface IBar1
{
}
public interface IBar2
{
}
public class Foo : IFoo
{
public Foo(string value, IBar1 bar1, IBar2 bar2)
{
}
}
I have reviewed the answer on SO here on how to achieve this: http://stackoverflow.com/questions/21785822/simple-injector-or-lightinject-pass-parameters-to-constructor?answertab=votes#tab-top
Which works, but this would mean that I would have to code the ctor for each instance I require whereas it’d be fantastic if the container could somehow still auto-resolve all of the parameters apart from the string.
Is there any way to achieve this?
Issue Analytics
- State:
- Created 8 years ago
- Comments:10 (5 by maintainers)
I think I have found a solution for you.
If fact, LightInject “almost” supported this out of the box and only minor brain surgery was needed to make this happen.
Let’s first take a look at the following unit test created for the sole purpose of this issue.
The RegisterConstructorDependency method has gotten an new overload that passes the runtime arguments supplied to the GetInstance method. This means that you can reason about the constructor parameter such as its type, declaring type and so on and then decide if you should fulfill the dependency using the given runtime argument. The rest of the dependencies are resolved as usual and you no longer need to be so explicit about the constructor dependencies even when using runtime arguments.
A new version of LightInject (4.0.3) has just been published to the official NuGet feed containing this new feature.
For reference here is the sample classes used in the test.
There is always a way to solve anything 😃
So you have something like this
What we could do here is scan for a certain pattern in the constructor of the target types and one such pattern could be that the first argument is a string and then we invoke the appropriate Register method such that when the GetInstance method is invoked with a string runtime argument, it would work as if you have explicitly registered the constructor.
What do you think? Would that be something that could work?