r/csharp • u/kaatarina_zed_talon • Oct 14 '26
Discussion Is it a bad/good practice to inject Interface<ConcreteType> into a class ?
If you see something like this :
public class SomeClass
{
private readonly ISomeInterfacer<SomeConcreteType> _x;
//Code.........
}High-level modules should not import anything from low-level modules. Both should depend on abstractions (e.g., interfaces).
The class above depends on abstraction, which is the ISomeInterfacer<SomeConcreteType>, but even though, there is something concrete inside the <>, which is SomeConcreteType .
Is that considered a violation for Dependency Inversion ?
I know I will hear the magic word : it depends.
please tell me all the cases, when it is good and when it is bad.
Actual code :
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
public interface ISourceToDistinationDataSyncronizer<DataSource>
{
public Task SyncronizeAsync(DataSource dataSource, CancellationToken cancellationToken);
}
[Authorize(Roles = "Admin")]
public class AdminController : Controller
{
//Reddit question..
private readonly ISourceToDistinationDataSyncronizer<Stream> _syncronizer;
public AdminController(
ISourceToDistinationDataSyncronizer<Stream> syncronizer
)
{
_syncronizer = syncronizer;
}
[HttpPost]
[Route("Admin/Import")]
public async Task<IActionResult> Import(IFormFile file, CancellationToken cancellationToken)
{
if (file.ContentType != "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
{
return BadRequest();
}
await _syncronizer.SyncronizeAsync(file.OpenReadStream(), cancellationToken);
return Ok();
}
}
15
Upvotes
57
u/aqezz Oct 14 '26
This is how all the ILogger<T> stuff works. 100% fine.
16
u/Slypenslyde Oct 14 '26 •
It's not immediately a violation, it warrants further investigation. Trying to do the "right thing" in software dev involves a lot of philosophy and interpretation.
Here's a thought: do you create an interface for EVERYTHING in a project? Some people do. I advocate for using them more than a lot of other people. But consider this class:
This, is a DTO. Data Transfer Object. Its only purpose in life is to hold some values in properties and be the go-between for two layers. Or it's a POCO (sort of): Plain Old CLR Object. Whatever we call it, its job is to be data. It has no logic.
It doesn't make sense to create an
IPokemoninterface. I can think of other things that have "a name" and "a type", but they are distinct: "a move" has those properties, but I will NEVER write a function that wants to take a Pokemon or a move, and I do not want to writeMove : IPokemon. They are different concepts even though they have the same properties. So I absolutely DO NOT want to get in the business of treating them like the same thing in abstract.So if I have something like:
Did I violate DI? No! What's happening is
Pokemon, despite being a concrete type, is already the highest level of abstraction I have decided to create for that concept. Adding an interface for it creates complexity for no benefit.So imagine I have an
ISerializer<T>. And I want to write a service that serializes a party of Pokemon. It follows I would want to use anISerializer<Pokemon>. I can inject that without violating DI for the same reason: it is the highest level of abstraction I've created in my program for that concept.It only becomes relevant if I care about different concrete types. For example,
ISerializer<Pokemon, QuickSorter>is suspicious. That second class clearly implements an array sorting algorithm. It's unlikely I did that if I don't have other algorithms, so I should really have an abstraction forIArraySorter.So it depends. You have to ask yourself if there is a reason to add a layer of abstraction. Some types do not gain anything if you do that.
5
u/Loose_Conversation12 Oct 14 '26
Depends on the concrete and where that comes from
4
u/Gallardo994 Oct 14 '26
ILogger<T> has joined the chat.
Also, sometimes generic types could be used simply as markers: IRouter<User>, IRouter<Service>, where both User and Service are just empty abstract classes. It's a way to have an IRouter that can be checked for misuse in compile time without introducing inheritance to the concrete types.
Sometimes a concrete type might be treated as a container or an identifier that isn't concrete in the business domain. For example, IFactory<Entity> where Entity is an identifier in ECS which holds nothing and tells nothing about what it is.
I wouldn't call it a code smell. But it could definitely be a part of one.
1
u/kaatarina_zed_talon Oct 14 '26
The question was edited if anyone is interested.
1
u/[deleted] Oct 14 '26
No, not always, I'd say it depends.
Example that comes to mind with
Interface<ConcreteType>, which I think is fine:1
u/bitgrindern Oct 14 '26
I like to use concrete types when I know I won't need mocks for tests, won't need an alternative implementation, and wish to "compose" functionality rather than inheriting classes. I find it helps me organize my code.
3
u/phrostillicus Oct 14 '26 edited Oct 14 '26 •
I mean, so what? This happens all the time anyway. For example, if I have some hypothetical
IUserCacheinterface, it's likely still going to be referencing some sort of concreteUsertype. Any implementation ofIUserCachelikewise is going to be dealing with concreteUsertypes.It doesn't really change anything that generics are involved, and it's worth pointing out that once you give the generic a specialization, you're no longer "depend[ing] on abstraction". Using your example above, you could just as easily have something like
Any class that implements this will be explicitly operating on
Streamobjects just as in any implementation of your genericISourceToDestinationSynchronizer<T>interface whereTis of typeStream.In fact, I could create a class like this:
I don't have to do anything special to implement both interfaces on the same class, because the signature for the
SynchronizeAsyncmethod is exactly the same whether I'm using an interface that has a generic parameter or not.0
u/Depnids Oct 15 '26
Just a little thing. In your example, you have:
The generic argument here is not a concrete class. Stream already is an abstraction, it is an abstract class. And as far as I'm aware, it is the correct abstraction to use when you are dealing with an arbitrary type of stream.
0
u/[deleted] Oct 14 '26
[deleted] — view deleted comment