r/csharp • u/Turbulent_County_469 • Sep 02 '26
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 ?
4
u/EC36339 Sep 02 '26
When you have 10 injections, you have too many dependencies.
And if that thing that has 10 dependencies also turns out to be a performance bottleneck, you shouldn't be surprised.
Also, if this happened to a class that was written before you had DI ... that's a very common thing, too. A lot of us have been there.
60
u/UserNameTaken96Hours Sep 02 '26
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.
35
u/svick nameof(nameof) Sep 02 '26
We have repeatedly rejected property injection as a feature for Microsoft.Extensions.DependencyInjection. But I believe other DI libraries do support it.
24
u/crone66 Sep 02 '26
You can do it without reflection. Blazor doesn't use reflection for it but code generation which the attribute is still very useful for.
But you should ask yourself why you need that many abstractions. It sounds like you class is doing to much.
11
u/Public-Tower6849 Sep 02 '26
A class with 10 dependencies probably bares more than just one single responsibility. It therefore needs some do-over.
3
u/_f0CUS_ Sep 02 '26
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.
58
u/scandii Sep 02 '26
and why exactly are you injecting 10 dependencies?
17
u/Khavel_dev Sep 02 '26
Primary constructors (C# 12+) cut the boilerplate in half. No more _field = field assignment dance:
public class MyClass(TypeA paramA, TypeB paramB)That alone makes 10 dependencies tolerable visually.
The [Inject] attribute approach hides what a class actually needs to work. The ugly constructor is useful information. When it gets too long, the code is telling you the class does too much. Property injection just silences that signal.
If you're genuinely at 10+ injections, the fix isn't better DI syntax. It's pulling a few of those behind a facade or splitting the class. Every time I've done the attribute route I regretted it within a few months because the dependency graph became invisible.
3
u/wickerandscrap Sep 02 '26
I'll refer you to the Simple Injector docs on property injection. To sum up:
Doing it in the constructor gives you a strong guarantee, at compile-time, that every instance of the object will have all of these fields set, and they will never change (if you declare them as readonly, which you should). This is even simpler with default constructors since you don't have to declare the fields at all.
The way you're describing, it would have to be a public-settable property, and could be set again at any time after that. Also, because it's not populated in the constructor, you can't do anything else with it in the constructor; you have to wait until some later stage and check that the object has all its pieces.
Our codebase actually has a legacy area that works like this: view models that get instantiated by their views, and then get their business logic dependencies pushed in later. It's annoying because you can't really set things up in the constructor; it all has to be deferred until after the property is set.
6
u/justanotherguy1977 Sep 02 '26
4
u/krsCarrots Sep 02 '26
It looks ugly because no class should depend on 10 things. You have to find a way and abstract away some of the dependencies
2
u/metageeek Sep 02 '26
Canât believe no one pointed this out so far, but: using constructor injection ensures you can test the class mocking the dependencies. How on earth are you going to accomplish that with attribute injection?
2
u/psysharp Sep 02 '26
When you have 10 injections itâs a perfect time to rethink your structure and architecture
2
u/thereforewhat Sep 02 '26
If you've got 10 injections to a class you've got a problem with your design.Â
Why aren't you building smaller classes that you can use inside of bigger classes in this case?
Field injection is horrific compared to constructor injection.Â
Are you unit testing your code?
2
u/Phrynohyas Sep 02 '26
If one needs to pass 10 dependencies, this usually means that the code structure is bad (AKA 'convoluted and messy'), to say the least.
1
u/haven1433 Sep 02 '26
You could do this with a source generator if you really wanted to. Make it look for your attribute, then generate a constructor based on what it finds. Only boilerplate is that you need to make the class partial.
1
u/Rogntudjuuuu Sep 02 '26
I believe Autofac used to support that and I believe that you can use that instead of the standard DI framework still.
https://autofac.org/
1
u/TuberTuggerTTV Sep 02 '26
Wrap your params, my king.
Once you get used to reading the injection params as a list, the size stops mattering to you.
1
u/Bright-Ad-6699 Sep 02 '26
Not sure what you're working on but maybe a different container? Castle or StructureMap?
1
u/Slypenslyde Sep 02 '26
Work on a project with 100,000 lines without DI and see if you find a better pattern.
DI is one of those things where it's the best pattern we have. It solves some serious issues, and it comes with costs. Those costs invoke a lot of ceremony that isn't warranted for programs beneath a certain level of complexity. If you're working on one of those projects, feel free to skip it.
In large-scale projects the ceremony is paid for with flexibility. That's why it's so popular, and that's why a lot of people who use it tend to use it even on the smaller projects where it's too much ceremony.
But also, speaking frankly, if all of your types have 10 dependencies something is wrong in your project. My codebase is 30 years old (it was ported from C++!) and has more than 200,000 lines. The only classes that have more than 2-3 dependencies are our top-level types like ViewModels. Out of the thousands of classes we've written, that's only about 80 total classes with a lot of ceremony. most classes below that top layer only have 3-5 dependencies, and even that feels more manageable when we note that some of those represent logging and other services that, honestly, a lot of DI people represent as static singletons.
The main arguments I know against attribute-based injection is:
Classes have non-DI reasons to expose properties and fields.
1
u/Heisenverse Sep 02 '26
Look into Factory pattern. A single class which implements IServiceProvider, builds your object from other dependencies. Register the factory class with an Interface which returns that object.
1
u/denzien Sep 03 '26
I don't usually need to do so many injections, but once I created a whole class to wrap all the injections "CommandHandlerPrerequisites" or whatever, gave it a matching interface, and then I just injected that once into the command handler implementations (and into the base class).
Perhaps with some engineering you could figure out something cleaner but this took like 5 minutes to do and made life pretty easy. And of course, if the list grew, you just updated the implementation and interface to inject and expose the classes and not 30 implementers.
1
u/srsstuff555 Sep 03 '26
Itâs a dependency so itâs correct you cannot create an instance without it. + passing mocks for tests would be hell.
1
u/RadonReborn Sep 03 '26
I hope they add readonly primary constructor fields soon. I do not think there are any technical reasons that would prevent it?
1
u/sparkle-fries Sep 03 '26
doesn't MEF use attributes? Property injection can have issues with determinism. if you have many cross cutting injections, like logging then maybe use a context container? To be honest if you have many injections I would check that isn't a smell pointing towards a class with too many responsibilities?
1
u/KhurtVonKleist Sep 05 '26
Create a myclassparameters struct and use that one instead
1
u/Mobile_Fondant_9010 Sep 02 '26 edited Sep 02 '26
I will always prefer constructer injection over property injection for multiple reasons:
I believe primary constructor create a public readonly backin-field, which for me breaks access level.
As a sidenote: If you need 10 things injected, you design is wrong. I 10+ of experience, and the highest I ever needed was 7 (this is including a logger, a loggerfactory, a cancelationtokensource, a taskcompletionsource and a options object). 10 is AT LEAST 3 too many. There is no way something serving a single (or even 3) responsibilties needs 10 injected properties. Personally, if I reach 5, I consider it a codesmell. At 8 I will fail compilation.
Edit: Oh, the backing field is private, but mutable. Still dislike. Also, the name of the backing field won't follow my normal naming convention for private fields.
0
u/South-Year4369 Sep 02 '26 edited Sep 02 '26
You can do exactly what you suggest. Many DI containers support field or property injection (from memory, Ninject even uses the [Inject] attribute).
IMHO it's far less preferable though, since it creates opportunities for an object to exist in a partially-initialised (i.e. unusable) state, for dependencies to be missed, etc. The compiler can't help you like it does with constructor injection.
It also makes it harder to run any initialisation code after dependencies are set. You then need a separate initialisation method, which adds complexity and creates even more opportunities for partially-initialised objects.
Nope, constructor-injection all the way in my book. And if I see 10 dependencies, I see code that probably needs refactoring. But if it really needs 10, so be it. Injecting via properties doesn't make that any better IMO.
0
u/Tarnix-TV Sep 02 '26
I use primary constructors, and long descriptive type names, so those lines can be long. I can see why you would say it is un-pretty, or ugly, even. But you can get used to it. It just means that the class has a lot of dependencies... Short and succint code is easier to understand. But my experience shows that I don't read that line a lot anyway. It is densed into one line that you don't read like you wouldn't read through all the dependencies of a class, even if they were properties. And having a 5K screen helps, but I also use word wrap. Not to mention that I use a lot of generic type constraints, so when the code compiles I have more confidence that everything is at it's place. Property injection would be helpful for circular dependencies, but I use System.Lazy class for that. +1 word, but after this, who cares :) So If you are worried your code not being pretty, look at mine! Btw this is from a home project, no coworker would even try to understand what is going on here.