My company has a shared library that has code like this
public interface IBaseService<TBaseUser> where TBaseUser : BaseUser
{
// snip
}
public class User : BaseUser
{
// snip
}
public class SomeService : IBaseService<User>
{
}
Various applications make use of this shared code. I am trying to write a base controller that takes in an IBaseService<BaseUser> in its ctor.
public class BaseController : Controller
{
public BaseController(IBaseService<BaseUser> service)
{
}
}
The code at the library level works exactly as I'd expect, but when I try to use it from a consuming application and pass in the derived type, i.e. a Service type, it fails with an invalid cast.
public class MyController : BaseController
{
public MyController(SomeService service) : base(service)
{
}
}
Is what I want to do possible?
Your IBaseService-iterface needs to be covariant:
interface IBaseService<out T>
This way you can assign an instance of IBaseService<User> to IBaseService<BaseUser>.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With