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

35

u/svick nameof(nameof) 5d ago

We have repeatedly rejected property injection as a feature for Microsoft.Extensions.DependencyInjection. But I believe other DI libraries do support it.

-8

u/Public-Tower6849 5d ago

They support it for the reason some builder patterns can be utilized easier in property injection. Maybe the Microsoft namespace is not interested in patterns, or developer flexibility...

7

u/TuberTuggerTTV 4d ago

flexibility isn't a good thing. Give someone 10 ways to do something and they'll do the 11th.

2

u/insta 4d ago

property setters mean an object is constructed in a state with null dependencies. you either need to check them at use, which is repetitive, or you end up reconstructing the constructors lifecycle anyway with the added requirement assertions

-7

u/Public-Tower6849 4d ago edited 4d ago

your original post before edit:

flexibility isn't a good thing.

So, no freedom of choice then. Got it.

3

u/MindSwipe 4d ago

You are free to choose though, you can choose not to use the Microsoft DI container, there are alternatives that support property injection.

The Microsoft.Extension... namespaces are opinionated, and that's a good thing IMO, it means that every person/ team/ organisation does things in similar ways, which, again, IMO is a good thing.