I have the following .
public interface IMyService<T>
where T: BaseModelType
{
Process(T input);
}
public class BaseModelType
{
...some property
}
public class SomeClass : BaseModelType
{
...some properties
}
public ServiceImpl : IMyService<SomeClass>
{
...the properties
}
Then I have a unity container where i register all the implementations of the generic interface. I want to be able to use the unitycontainer’s resolve method to get the interface, then do some work on it. At the time when i want to use the Resolve method i have the type in runtime
new UnityContainer.Resolve(myTypeVar)
Can I somehow cast this to be
IMyService<BaseModelType> value = new UnityContainer.Resolve(myTypeVar) //want to cast it here from object.
So that i can call the Process method that the interface defines.
No, because
IMyService<SomeClass>does not implementIMyService<BaseModelType>. If you look at the implementation of the Process method:This clearly assumes that you’re giving it a
SomeClass. It should be able to safely access any members ofSomeClass. But if you called this method with aBaseModelTypeas the parameter, that wouldn’t work, would it?Assuming that you know at runtime that your
inputargument is going to be of the right type for the given genericIMyService<T>interface, you have two options:Add a non-generic parent interface for
IMyService, which takes aBaseModelType. In your service implementations, you can implement this method by casting the input to the expected type for that implementation. This requires more code. But you could alleviate that somewhat by having a generic abstract base class that implements this method so the other implementations don’t have to.