2

There is an interface which inherits the generic interface.

Here is generic interface

public interface IBaseService<TEntity> where TEntity : BaseEntity
{
}

Interface which inherits generic interface

public interface IChatService :IBaseService<Messages>
{
}

Then i have a class which takes the generic interface in the constructor as a parameter.

public class BaseApi
{
    IBaseService<BaseEntity> _baseService;

    public BaseApi(IBaseService<BaseEntity> baseService)
    {
        _baseService = baseService;
    }
}

When i pass the interface object which implements the generic interface it doesn't allow me to pass the object of the interface, it asks to pass generic interface.

Here is error: enter image description here Any solution? Thanks in advance, sorry for bad english!

Malik Rizwan
  • 759
  • 1
  • 10
  • 31

2 Answers2

2

This is quite logical. Let's simplify matters a bit by renaming our types and creating a new example:

public class BaseApi
{
    public BaseApi(IBucket<Fruit> baseService) { ... }
}

And our IBucket<Messages> represents a concrete type of fruit (apple):

public interface IChatService :IBucket<Apple>
{
}

A bucket of apples is not the same as a bucket of fruit because you can put an orange in the latter and you cannot do this with the former.

To deal with this you could either change the signature of IChatService:

public interface IChatService :IBaseService<BaseEntity>
{
}

Or pass the expected IBaseService<Messages> type to BaseApi's ctor.

Fabjan
  • 13,506
  • 4
  • 25
  • 52
0

You can fix this with covariance. But only if your argument can be covariant

public interface IBaseService<out TEntity> where TEntity : BaseEntity
{
}

https://learn.microsoft.com/en-us/dotnet/standard/generics/covariance-and-contravariance

Dmitrii Dovgopolyi
  • 6,231
  • 2
  • 27
  • 44