Just saw something really strange that I have never seen before as a #dotnet dev:
Using a `record` for a service that is registered in DI.
Are there any devs here that do this and can tell me why? Any huge benefits I'm not seeing here?
I thought about this since I posted it and think that the cons outweigh the pros for using records for services.
Some cons I see:
1. Problems with libs: some libs require you to inherit from a class
2. Exposed dependencies: injecting something inside your Records will store it in a public prop
3. unnecessary IL code: for my services I don't really care for value comparison
The (only?) pro so far:
1. less boilerplate code
@dr_cox1911 Oh yes! I wrote about using it for MediatR handlers, it really shortens the code and removes repetition https://tpetrina.com/blog/2022-11-07-records-simplify-dependency-injection-for-mediat-r-handlers
@tpetrina Thanks for pointing out that usecase, that's one advantage I thought of as well. I kinda had an argument with someone who uses records now for everything and that I find problematic. E.g. you can't inherit from libs like #FluentValidation with records.
For the usecase you blogged about I think it's nice, but with .Net8 I would still prefer classes with primary constructors I guess.
@dr_cox1911 I agree, but when I wrote this (and still) .NET 8 is not something I can use in production.
Also, side note: C# is becoming too complex :/
@tpetrina @dr_cox1911 oh that’s interesting!
I ended up solving the repetition issue with a source generator. https://github.com/distantcam/autoctor
@dr_cox1911 looking at the MS documentation for records it seems it’s mostly syntax on top of a class. So no value to go a wholesale change things.
But it does have formatting for easier debug display, automatic equality comparisons, some editing features for immutability. So it could be easier/quicker to define things that way and not need to add a bunch of extra methods that are already automatically generated.
Or just could be habit. Record is very simple syntax for a data transfer/storage class.
@cambirch Thanks for your reply, I know and use records for the scenarios that your last sentence depict: data
For this they are awesome, just don't really see the appeal to use them for my services.