Extending interface with generic is not assignable to parent c#

Viewed 587

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!

2 Answers

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.

Related