General Factory Method for Creating a Derived Class from a Base Class

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
    {
        // Use reflection to create the derived type instance
        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.

+3
source share
2 answers

, , , , . :

Type implementationType = typeof(T).Assembly.GetTypes()
                                   .Where(t => t.IsSubclassOf(typeof(T))
                                   .Single();
return (T) Activator.CreateInstance(implementationType);

, .

, - , , , . ( .)

+4

, IOC. Autofac, . IOC, .

+1

All Articles