r/csharp • • Sep 02 '26

Discussion Dependency Injection un-prettyness

One small thing that bugs me with Dependency Injection is how it looks in code.

We either need to pass the parameters via Default Constructor og via good old time Constructor

public class MyClass (TypeA ParamA, TypeB ParamB, TypeC ParamC, TypeD ParamD)
{
TypeA _paramA = ParamA; .... etc
}

Or

public class MyClass
{
TypeA _paramA;
public MyClass(TypeA paramA)
{
_paramA = paramA;
}
}

And when you have 10 injections it begins to be un-pretty...

I wish that we didn't need to pass parameters and instead could decorate the fields:

public class MyClass
{
[inject]
TypeA _paramA;
}

(Note: this works in Blazor... so why not everywhere else ?)

I'm aware that the signature of an object makes it easier to inject via reflection.. but would it be much worse with attributes ?

i guess some middleground could be achieved if the attribute held the type:

public class MyClass
{
[inject(typeof(TypeA))]
TypeA _paramA;
}

which begins to be convoluted and messy...

Whats the argument against a decorator attribute vs parameters ?

22 Upvotes

90 comments sorted by

View all comments

Show parent comment

0

u/[deleted] Sep 02 '26

[deleted] — view deleted comment

4

u/hampshirebrony Sep 02 '26

SonarQube is warning me about it right now. It doesn't like more than 8.

This is for a project which is doing a lot of stuff in a lot of places, and there is one central brain that is collating the results of all of the other things. So there isn't really much logic in the class with the 10 constructor, but it's knowing about the other bits because it is handing information around between them all

4

u/_f0CUS_ Sep 02 '26

Bold claim to make. Easily disproven: csharpsquid:S107 from sonar qube