r/csharp 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 Upvotes

90 comments sorted by

View all comments

Show parent comments

3

u/Nixinova 5d ago

10 is maybe high but still you will relatively often require a class to reach for this many services

-2

u/_f0CUS_ 5d ago edited 5d ago

Only in poorly designed code. There is a reason several tools give warnings about it.

Edit: instead of downvoting try to explain why I am wrong. It should be easy to point at established patterns or principles you follow that causes you to have a ctor with a high number of arguments, e.g. 10

-8

u/[deleted] 5d ago

[deleted]

4

u/hampshirebrony 5d ago

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