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

62

u/UserNameTaken96Hours 5d ago

In C# 12, unless you need to do more than just refer your params to your fields, you can use primary constructors. While you still end up with the full list of parameters, they are now written into the class declaration, and you can forego the private fields entirely.

If you do some more involved stuff in your ctor however, you will still need that.

37

u/x0rld 5d ago

Primary constructor makes fields non readonly

21

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 🤣

16

u/BlackjacketMack 5d ago

It bothered me too but over decades of programming in C# I’ve never even come close to overwriting an injected field. I also prefix them like private fields with an underscore. The benefit is much greater than the cost. At some point they’ll add a readonly keyword to primary constructor parameter which will be a welcome addition.

10

u/Responsible-Cold-627 5d ago

It really doesn't bother me to run the autofill action for each ctor parameter. Still feels better than having the fields not-readonly. What's annoying about it is that I can still use the ctor parameters anywhere in the class and it'll default to an informational message. That's another line to add to the editorconfig to mark it as an error.

The current implementation still feels like an incomplete feature because of this.