DIForFunctions – Improving constructor–part 5
I have received a suggestion : what if we just put into constructor what we need , and everything else ( such as ILogger ) are into fields ?
The Roslyn Source Code Generator will generate a constructor that calls the this constructor and will assign fields needed.
Let’s give an example : We wrote
public partial class TestDIFunctionAdvWithConstructor2Args
{
[RSCG_FunctionsWithDI_Base.FromServices]
private TestDI1 NewTestDI1;public TestDI2 NewTestDI2 { get; set; }
public readonly TestDI3 myTestDI3;
private TestDIFunctionAdvWithConstructor2Args(TestDI3 test, TestDI2 a)
{
myTestDI3 = test;
NewTestDI2 = a;
}}
and the generator will generate a new constructor with the required field
public partial class TestDIFunctionAdvWithConstructor2Args
{
public TestDIFunctionAdvWithConstructor2Args
(TestDI3 test, TestDI2 a, TestDI1 _NewTestDI1) : this (test,a)
{
this.NewTestDI1 = _NewTestDI1;
}//end constructor}//class
The code is non trivial – to find if a constructor exists, take his fields, generate new constructor with all fields.
But , as anything in IT , it is doable .
Leave a Reply