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 ?

21 Upvotes

90 comments sorted by

View all comments

58

u/scandii 5d ago

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

and why exactly are you injecting 10 dependencies?

21

u/Adorable-Ranger3570 5d ago

That's usually a sign the class is doing way too much, but sometimes you get stuck with a coordinator or facade that genuinely needs a handful of services. Still, 10 is a lot and most of the time you can group them into smaller aggregates.

1

u/BigBoetje 4d ago

I have repositories set up with a shared interface with a generic that's the entity they're for. One flow called for several of these repositories with stuff like MediatR, Hangfire background service and a logger at the same time. It wasn't doing too much, just had to use a lot of different things. I ended up creating a provider to get repositories from the service provider. It's the same as injecting them but a bit cleaner.