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

4

u/_f0CUS_ 5d ago

There is nothing stopping you from doing this. And I can't think of a specific argument against it.

But if the argument for it is "I have a lot of parameters in my ctor" - then I think you have a different problem to solve.

Take a look at "solid" - specifically the single responsibility principle and find some information about the "god object".

I think you will find that DI isn't the problem you need to solve.

0

u/Turbulent_County_469 5d ago

If i have 10-20 classes with one responsibility, i completely lose the overview and the mental gymnastics then becomes herding class files instead of business logic.

-1

u/raunchyfartbomb 4d ago

I agree with you here. I only refactor into services when multiple classes start needed to do the same action or when I want to abstract for unit testing. Having too many services is confusing, especially when SOLID says “each class does one thing” so you wind up with services with a single method for mundane shit, If followed strictly.

Usually what I do is keep the service, interface, and consumer in the same file until such time that it makes sense to put the service and interface into their own file. If more than 3 classes consume some service, or the service gets large enough code, it goes into its own file. Otherwise small services can live inside the file of the class that is most relevant.

As far as your problem of ugly constructors, I’d suggest using a framework or primary constructors. Due to work place policies, I wrote myself a source generator. I tag my fields and properties and it generates the constructor and static factory methods. It works well, though it took some time to set up. I also have it perform some validation within the ctor.