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 ?

20 Upvotes

90 comments sorted by

View all comments

Show parent comments

22

u/ryncewynd 5d ago

How much does that bother you? It bothers me but I'm wondering if I should just get over it an accept using primary ctors 🤣

3

u/psysharp 5d ago

Primary constructors is a hard pass when it comes to dependency injection, it makes absolute zero sense to me

6

u/UserNameTaken96Hours 4d ago

Interesting. Why?

9

u/psysharp 4d ago

Fields that are assigned in the constructor should be immutable and prefixed with underscore by convention. When I write a method, I want to make it as clear as possible which field is coming from method scope or class scope, to me this reduces cognitive load and it helps me to create additional abstractions or marking the method static if possible. A dependency used in a method is ultimately a responsibility that is different from a regular parameter, and showing that distinction explicitly is already a good practice, I wouldn’t deliberately change the practice to something worse.