You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I expected constructor two to be used with parameter of type ClassB but grace injects a newly created ClassA in the first constructor instead.
classClassA{}classClassB{}classInjectedClass{publicClassAClassA;publicClassBClassB;publicInjectedClass(ClassAclassA){ClassA=classA;}publicInjectedClass(ClassBclassB){ClassB=classB;}}publicclassConstructorSelection{[Fact]publicvoidTest(){varcontainer=newDependencyInjectionContainer();varfuncA=container.Locate<Func<ClassA,InjectedClass>>();varclassA=container.Locate<ClassA>();varinjectedA=funcA(classA);varfuncB=container.Locate<Func<ClassB,InjectedClass>>();varclassB=container.Locate<ClassB>();varinjectedB=funcB(classB);Assert.Equal(classA,injectedA.ClassA);Assert.Equal(classB,injectedB.ClassB);//first constructor used, with newly created ClassA and classB not used.}}
The text was updated successfully, but these errors were encountered:
Grace makes some trade offs to achieve the performance it does. One of those trade off is that it's going to pick one constructor for an object and stick with it. For corner cases like this it's not going to work very well.
Let's take a step back though because constructor injection is supposed to be the contract specifying the dependencies an object depends on to be constructed. What does it say when there are two constructors with two different parameter types?
My general rule of thumb these days is to have one constructor. If you want/need multiple have one main constructor that take all parameters and the others call the main constructor. That said it's usually far easier and more descriptive to have one constructor/one way to construct an object.
I understand the point, I ended up with creating two inherited classes, one for each case. Not as elegant in my case but maybe more readable, so it's ok. Thank you for the time pasted.
I expected constructor two to be used with parameter of type ClassB but grace injects a newly created ClassA in the first constructor instead.
The text was updated successfully, but these errors were encountered: