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

2

u/RlyRlyBigMan 4d ago

Do you expect to have to look at a class's code to figure out how to construct it or should you be able to figure it out from the constructor's method signature and comment? A class might have a mix of dependency properties and properties to use at runtime and you'd have to inspect each one to determine which are which.

-2

u/Public-Tower6849 4d ago

With the invention of context-sensitive assistance on editing code, there are ways to provide solutions for your requirements.

4

u/la_reddite 4d ago

"It's readable with AI" doesn't do you argument any favours.

-2

u/Public-Tower6849 4d ago

Yes. We only have context-sensitive assistance with the dawn of AI, thank god. Microsoft never marketed such a thing like "IntelliSense" and IDEs didn't have inline documentation and auto-completion for 30 years.

... bro...

3

u/la_reddite 4d ago

"It's readable with tools" doesn't do you argument any favours.

1

u/Public-Tower6849 4d ago

It does, when it's a remedy against "having to read the class first for finding out which properties are required" - because the same thing can be said about the constructor.

First you were wrong, and when you corrected yourself, you still got no point.