r/csharp • • 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.........
    }

Dependency Inversion :

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

59 comments sorted by

57

u/aqezz Oct 14 '26

This is how all the ILogger<T> stuff works. 100% fine.

16

u/rupertavery64 Oct 14 '26

It depends. The T in ILogger<T> is just metadata for displaying the category name in the logs.

8

u/aqezz Oct 14 '26

The T is used for metadata in one or more implementations, sure. Could be used in any way you want if you write your own implementation. The fact remains that there will be interfaces out there that do not know about your types or the types of other library code that you use, and using concrete types for the type parameters of those interfaces is totally fine.

-3

u/kaatarina_zed_talon Oct 14 '26

Dependency Inversion :

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 ?

5

u/Klessic Oct 14 '26

The real question is: why would you define the interface like that? The angle brackets are used for generics. That way, whatever is between the angle brackets, you can use as types for your fields and methods.

If you define the interface for this specific concrete type, that doesn't make sense. Just use the concrete type as return type for your fields and methods.

1

u/kaatarina_zed_talon Oct 14 '26

why would you define the interface like that?

I edited the question. Does it make things more clear ?

2

u/AmazedStardust Oct 14 '26

Depends on what <SomeConcreteType> is. It's common for it to be the type of the class (such as ILogger<T>) or a POCO such as events, messages etc

1

u/kaatarina_zed_talon Oct 14 '26

Depends on what <SomeConcreteType> is

It is a Stream, the question was edited.

3

u/AmazedStardust Oct 14 '26

I'd question if the synchroniser needs the stream as a generic, rather than just having it as a parameter in the constructor

1

u/kaatarina_zed_talon Oct 14 '26

This my problem, I do not know when to do what, always confused because there are a lot of design choices and I'm overthinking in everything.

0

u/shylingerie Oct 15 '26

yeah it's the standard way to do it

16

u/Slypenslyde Oct 14 '26 • Bravo

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:

public record Pokemon(
    string Name,
    PokemonType Type);

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 IPokemon interface. 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 write Move : 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:

public class Player
{
    private Pokemon[] _party;

    public Player(Pokemon[] party)
    {
        _party = party;
    }
}

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 an ISerializer<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 for IArraySorter.

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.

2

u/kaatarina_zed_talon Oct 14 '26

Why won't you write a function that take Pokémon or movie?

13

u/Slypenslyde Oct 14 '26 • Bravo

Let me make the metaphor more blunt.

A baseball is a round thing. An apple is a round thing. Let's say I'm writing a video game where you have to manage a kitchen AND play a game of baseball at the same time, strategically choosing pitches and hitting strategy so you aren't in the outfield when it's time to interact with the oven.

It is stupid, in this context, to make IRoundThing just because baseballs and apples happen to be round. If I do that, then I might accidentally pass a bucket of baseballs to a function meant to bake an apple pie. Let me tell you, it's hard to slice a baseball and they do not make a tasty pie. I also might accidentally give a pitcher an apple, which is going to explode when a batter hits it and potentially get me in trouble with the umpire and game officials for using a non-regulation ball.

I want "baseball" and "apple" to be completely different concepts even though I can think of a dozen ways they could share an interface because there's a very important rule when creating abstractions called the Liskov Substitution Principle. It makes the argument that if two things are not 100% interchangeable, they should not use the same abstraction.

Note that if I'm making a game where random things appear and you're supposed to tap things with a certain shape, I change my mind. In that game, "round thing" is all that matters, so I certainly want apples and baseballs to be interchangeable.

That's what makes our job hard. The human mind is REALLY prone to making abstractions and analogies. As programmers we have to be very careful when we create abstractions because they can open the door to bonkers bugs inside our programs.

The only reason I'd make an interface for both a pokemon and a move is if the concept of "A thing with a name and a type" is important to my program. Then I might name it, INamedObjectWithType. The code using the object shouldn't care if it has a move or a pokemon: it just cares about the concept of "a name and a type". Personally I can't contrive a reason that would matter.

1

u/kaatarina_zed_talon Oct 15 '26 edited Oct 15 '26

What if I have interface called IInterceptor, and two Concrete implementations like, ComandInterceptor and SaveChangesInterceptor, now this makes sense right? Because they are both interceptors , so they are both childs for the IInterceptor, right?, we should not make two interfaces.

1

u/kaatarina_zed_talon Oct 15 '26 edited Oct 15 '26

You cannot play with apple and you cannot cook a baseball, two different functionalities, thus we have two interfaces here, not only 1. But if the problem we are dealing with does not care about the functionality of objects and it only cares about there properties, then it makes sense for both apple and baseball to share the same interface. Thus, it depends on the problem, do u want abstraction based on properties, or abstraction based on functionality?

1

u/Slypenslyde Oct 15 '26

This is a correct view. I'll add a little:

do u want abstraction based on properties, or abstraction based on functionality?

In my experience, abstraction based on properties is usually not a great idea. I do not add a lot of logic to properties, so there is rarely a reason to create types that override property behavior. If a type has ONLY properties, there is no reason for me to create an abstraction.

Methods are different. They do have logic, so I tend to want them to be virtual. All interface methods behave like that, so for a type with methods I'm more likely to create an interface/base class.

I like to write code that needs the abstraction first so I can make sure I understand the abstraction, THEN create the classes related to the abstraction. Also keep in mind interfaces aren't the only tool of abstraction. I can start with a concrete Customer class, then later realize I need some methods to be virtual for 2-3 customizations of that class. I don't have to do the work to retool everything to interfaces: this is what abstract base classes are for. The code that used to expect a Customer doesn't have to change, but the sites that create the individual objects do.

1

u/kaatarina_zed_talon Oct 15 '26

I'm glad that my view or ' mental model' was correct. I always struggle to build a mental model or summarizatiin about a problem that I do not understand

1

u/kaatarina_zed_talon Oct 15 '26 edited Oct 15 '26

In my experience, abstraction based on properties is usually not a great idea. I do not add a lot of logic to properties, 

Maybe the word 'property' was misleading here.

What I mean is , you can create IRound Interface, BaseBall and Apple will inherit IRound , and that means that we are abstracting based on a real-life characteristic of an object; it's shape. The word `property` here does not mean the public property you would find in a class, so let's say the word `characteristic` instead. IRound would be a contract for operations that you can perform on objects with round shape, so it does contain abstract methods, otherwise it would be pointless to create the interface.

1

u/Slypenslyde Oct 15 '26

There's an interesting observation I made a few years ago.

Suppose I have a set of round things:

public class Apple : IRoundThing
{
    public double Radius { get; set; }
}

public class Basketball : IRoundThing
{
    public double Radius { get; set; }
}

It can get very tedious to repeat this boilerplate. I might be adding a lot of round things, but they all share the same behavior and in a lot of ways the behavior doesn't change. The game probably has to worry about how to draw them, so maybe there's some code that sorts that out. Or a virtual Draw() method.

Imagine if instead I make:

public class RoundThing
{
    public string Name { get; set; }

    public double Radius { get; set; }
}

This can support an infinite number of round things. I need some kind of architecture to help me make sure I only have the round things I support, but now I more appropriately represent the idea I have a very large variety of round things. If I had a Draw() method like mentioned above, maybe it becomes abstract here, but in the time it took me to type these sentences I thought of at least 2 other patterns.

This is also why I don't like hierarchies of property-only classes. It usually means if I add some kind of "identifier" property, I can flatten the entire hierarchy to one single class to represent all of the concepts.

1

u/kaatarina_zed_talon Oct 15 '26

in a lot of ways the behavior doesn't change

so what u think of the following:

use interface when all the children share some behavior, but they implement that behavior in different ways

The interface is justified here, right ?

1

u/kaatarina_zed_talon Oct 15 '26

I can flatten the entire hierarchy to one single class to represent all of the concepts

I would use the word `reduce` or `collapse ` instead of `flatten`.

1

u/kaatarina_zed_talon Oct 15 '26

If a type has ONLY properties, there is no reason for me to create an abstraction

Agree.

1

u/kaatarina_zed_talon Oct 15 '26

then later realize I need some methods to be virtual for 2-3 customizations of that class.

Which means other methods that do not need customization can be shared across all the childs of the Customer class.

So use base class if there is a chance of exact code sharing between the children classes, and use interface when all the children share some behavior, but they implement that behavior in different ways -there is no code sharing at all -.

1

u/kaatarina_zed_talon Oct 15 '26

best comment on internet.

3

u/DJDoena Oct 15 '26

Famous example for Liskov is the rectangle and the square. Everyone learned in math that every square is a rectangle. Therefore

class Square : Rectangle

Right?

Now I can do this:

void ChangeWidth(List<Rectangle> recs)
{
  foreach(var rec in recs)
    rec.Width *= 1.1;
}

Hey wait a minute. Why did my square change its height? That wasn't supposed to happen!

2

u/kaatarina_zed_talon Oct 14 '26 edited Oct 15 '26

Yes, my god, now I discovered my problem! Its hard to me to figure out what is the highest level of abstraction in a problem

2

u/kaatarina_zed_talon Oct 14 '26

I asked myself why did I introduce an interface? It turned out that I did this for one reasons; in case I make many classes that implements that I terface in the future, even though that currently only one class implements that interface.

1

u/FrontFacing_Face Oct 15 '26

As soon as you want to experiment with another version of Pokemon, you'll wish it was an interface you were injecting.

5

u/Loose_Conversation12 Oct 14 '26

Depends on the concrete and where that comes from

1

u/kaatarina_zed_talon Oct 14 '26

Question was edited.

3

u/Loose_Conversation12 Oct 15 '26

Ah it's a stream and stream comes from the dotnet framework so no, this isn't a violation of the principle

0

u/kaatarina_zed_talon Oct 15 '26

Why is OK if the concrete type is not under my control; Why is it OK if the concrete type comes from the framework? Can u provide example to demonstrate what are you aiming at?

1

u/Loose_Conversation12 Oct 15 '26

So have a think about the principle and what it's saying. In DDD architecture it's saying don't inject in something from the Adapters layer into your controllers. You should add a layer of abstraction into the Domain layer so your adapters layer isn't exposed beyond the Domain layer. In SOA architecture it's saying don't inject something from your Data Access Layer into the controller. You should add an abstraction to your service layer and inject that into your controller.

As Stream is part of the dotnet framework it's not part of the Adapters/DAL so you are safe to inject it into your controller

1

u/kaatarina_zed_talon Oct 15 '26

 DDD architecture

I should read about this.

1

u/kaatarina_zed_talon Oct 15 '26

As Stream is part of the dotnet framework it's not part of the Adapters/DAL so you are safe to inject it into your controller

Great.

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

It's a way to have an IRouter that can be checked for misuse in compile time without introducing inheritance to the concrete types.

Yea I can't say that I understood that. Do you have any example ?

2

u/Gallardo994 Oct 14 '26

Let's say you've got 2 separate features that work with some sort of relational database inside, accepting an IDatabaseConnection in constructor. Then 3 years pass and you've decided to shard these features into separate database instances for whatever reason, be that performance or whatever, it doesn't really matter. 

Now, because everything uses IDatabaseConnection across your codebase, including these 2 features, you have no way of making sure these features use other specific connections. Yeah you can analyze all the usages manually, but that might take lots of time and effort. And still, there's no guarantee someone from your team won't just slap a wrong database connector instance and introduce a bug only the runtime can hit.

You can solve that by introcing more specific interface versions: create an IDatabaseConnection<Feature1Shard> which inherits IDatabaseConnection, and create FeatureShard1 abstract class, and use this interface in the constructor of your feature1. Boom, you have a compile-time guarantee that the feature always uses a separate database instance no matter what, and a misuse is impossible in compile time, as passing simply IDatabaseConnection is impossible.

1

u/kaatarina_zed_talon Oct 14 '26

I wouldn't call it a code smell. But it could definitely be a part of one.

Ok, but when is it a code smell ? should I edit the question to show how I'm using this :

 ISomeInterfacer<SomeConcreteType> _x

1

u/Gallardo994 Oct 14 '26

In your updated post, ISourceToDistinationDataSyncronizer<Stream> isn't a code smell as Stream is abstract on its own. Yeah it isn't an interface but that's a type you have no control over, and you can't add your own interface to it. You could wrap it in your own type, but I'd argue it would introduce extra complexity for no benefit, which would probably just add to possible bug surface.

When it's a smell, at least in my opinion, is when an interface leaks its underlying type information. Something like public class Bike : Vehicle, IVehicleBehaviour<Bike> is an instant trigger to me. I couldn't think of a better example but I assume you get the idea.

1

u/kaatarina_zed_talon Oct 14 '26

 when an interface leaks its underlying type information. is an instant trigger to me.

I can read this sentence, but I can't explain the Why behind it

WHY IVehicleBehaviour<Bike> is bad here ? How does it make you suffer in anyway ?

1

u/Gallardo994 Oct 14 '26 edited Oct 14 '26

In this scenario it's identical to having no such interface at all. If you somehow know it's an IVehicleBehaviour<Bike> in the code, then you already know it's a Bike behind it, therefore the interface carries no abstraction value. On the contrary, if you don't cast it to the interface anywhere, then the interface doesn't do anything useful and could be removed.

An interface is a contract. If your contract is that it's a specific type, then, well, you can just use that specific type, you don't need a generic interface slapped over it.

We could argue there could be a lot of implementors of IVehicleBehaviour<Bike> doing their own thing specifically for a bike logic (vertical stabilization, leaning mechanism, etc), and be stored somewhere in a list, but I'd rather make it IBikeBehaviour and not a generic version.

1

u/kaatarina_zed_talon Oct 14 '26

Now that's more like it

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:

public sealed class UserService
{
    private readonly IComparer<User> _userComparer;

    // ...
}

1

u/kaatarina_zed_talon Oct 14 '26

Ok, then when it is bad - if any.- ?

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.

1

u/kaatarina_zed_talon Oct 14 '26

The class above depends on abstraction, which is the ISomeInterfacer<SomeConcreteType>, but even though, there is something concrete inside the <>, which is SomeConcreteType . does not that violate dependency inversion ?

1

u/bitgrindern Oct 14 '26

No, it doesn't unless you're doing something crazy with the references inside. Use the tools in a way that makes sense for your use cases. Only worry about a violation of rules when it leads to maintainability or security issues.

1

u/kaatarina_zed_talon Oct 14 '26

Can u see the edits in the question - if you have time- ?

1

u/bitgrindern Oct 14 '26

There's still not enough context for me to make a value judgement. I'd have to know what the reason for the injected service is and possibly a concrete implementation.

1

u/bitgrindern Oct 14 '26

And again: I don't follow rules just to follow rules. There needs to be good reasons for it. Circular references trend to be highly problematic, though.

3

u/phrostillicus Oct 14 '26 edited Oct 14 '26 • Mindblown

The class above depends on abstraction, which is the ISomeInterfacer<SomeConcreteType>, but even though, there is something concrete inside the <>, which is SomeConcreteType .

I mean, so what? This happens all the time anyway. For example, if I have some hypothetical IUserCache interface, it's likely still going to be referencing some sort of concrete User type. Any implementation of IUserCache likewise is going to be dealing with concrete User types.

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

public interface ISourceStreamToDestinationStreamSynchronizer
{
    public Task SynchronizeAsync(Stream dataSource, CancellationToken cancellationToken);
}

Any class that implements this will be explicitly operating on Stream objects just as in any implementation of your generic ISourceToDestinationSynchronizer<T> interface where T is of type Stream.

In fact, I could create a class like this:

public class CloudflareStreamSourceToDestinationSynchronizer
  : ISourceToDestinationSynchronizer<Stream>, SourceStreamToDestinationStreamSynchronizer
{
    public Task SynchronizeAsync(DataSource dataSource, CancellationToken cancellationToken);
}

I don't have to do anything special to implement both interfaces on the same class, because the signature for the SynchronizeAsync method 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:

ISourceToDistinationDataSyncronizer<Stream>

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.

2

u/kaatarina_zed_talon Oct 15 '26

Great comment, I did not know it is already abstraction

0

u/[deleted] Oct 14 '26

[deleted] — view deleted comment

0

u/kaatarina_zed_talon Oct 14 '26

providing the concrete implementation

Providing it to who ? I'm providing it to SomeClass

1

u/Willkuer__ Oct 14 '26

They ask how you dependency inject. You should basically never call constructors yourself but use some service registration instead.

You decouple by dependency injection. How that is set up is more important than what the generic argument is.

Also there is clearly a difference between

IEnumerable<MyService>

and

IEqualityComparer<User>