✅ Use static class or DI?

I have a situation where i am not sure, whether i should use dependency injection or just a static class. In my software, some clients are connection to a server. After the connection is set up, some data is stored (basically a dictionary with an client id + some data). In my current approach, i would just use a class "ClientCache" containing the cached data and a static dictionary with an id as key and a ClientCache as value. I chose this approach, as the ClientCache does not have any dependencies or context. If i register it to the service container, it would just be a singleton. Using DI for this specific class would not have any advantages at all (it just would mean a little more work). That said, there is one problem: the testing. The static dictionary is shared between all tests. Therefor i need to manually ensure, that the id is unique in all tests. Apart from that, everything is testable very well and there are no drawbacks if i am not using DI. Now my question: is it fine to give the developer the "responsibility" to ensure, that the client ids are unique or should i use the DI approach instead? Basically i think the static approach would be way cleaner, but i am not sure if that justifies the risks of invalid test cases/test setups (i think rather small risks, as the behavior would probably be pretty inconsistent if the tests use the same id) Thanks in advance for any input on this topic!
6 Replies
Angius
Angius11mo ago
Di will definitely be the safer approach Not just for testing, but because you would have to explicitly inject it as a dependency Meanwhile, a static class is implicitly available anywhere with zero restrictions
Stevvvvvvvvvvvvvvvvvie
Architectural principles
Architect Modern Web Applications with ASP.NET Core and Azure | Architectural principles
Yawnder
Yawnder11mo ago
@stevvvvvvvvvvvvvvvvvie Imo, static classes are great for converters, or "simple helpers" that just do short computation. I like to make them stateless generally. Go with a singleton I'd say.
Robbiew.Online
Robbiew.Online11mo ago
You could also introduce a factory, which when you're not testing returns back your static cache, but in tests could return a different one for your required test.
Nowadays I'd go for IoC unless it's a utilities class like a unit converter, string helper, etc. where you know you'll never need a variant of it, ever.
Stevvvvvvvvvvvvvvvvvie
Ok thanks, i will use the di/singleton approach
Accord
Accord11mo ago
Was this issue resolved? If so, run /close - otherwise I will mark this as stale and this post will be archived until there is new activity.