I am creating a factory method that uses a generic abstract type type to return an instance of a specific derived type using reflection. E.g.
public abstract class ServiceClientBase : IServiceClient
{
}
public abstract class Channel : ServiceClientBase
{
}
public class ChannelImpl : Channel
{
}
public class ServiceClientFactory
{
public T GetService<T>() where T : class, IServiceClient
{
T instance = typeof(T).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(string) }, null).Invoke(new object[] { endPointUrl }) as T;
}
}
Using:
Channel channelService = factory.GetService<Channel>();
The problem is that I cannot find any elegant way for the factory method to create an instance of the derived type passed in by the abstract base type in the method. The only thing I can think of is to maintain a dictionary containing a map between the abstract base and the corresponding derived class, but it seems to me like the smell of code. Can anyone suggest a better solution.
koder source
share