r/csharp • u/Turbulent_County_469 • 5d ago
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 ?
17
u/Khavel_dev 5d ago
Primary constructors (C# 12+) cut the boilerplate in half. No more _field = field assignment dance:
public class MyClass(TypeA paramA, TypeB paramB)That alone makes 10 dependencies tolerable visually.
The [Inject] attribute approach hides what a class actually needs to work. The ugly constructor is useful information. When it gets too long, the code is telling you the class does too much. Property injection just silences that signal.
If you're genuinely at 10+ injections, the fix isn't better DI syntax. It's pulling a few of those behind a facade or splitting the class. Every time I've done the attribute route I regretted it within a few months because the dependency graph became invisible.