Creating instances of classes derived from a certain base type, using reflection

Creating instances of all classes of a certain type (in the case below, all classes derived from IBroker)
you simply invoke them as follow:

internal void LoadAll()
    var BaseType = typeof (IBroker);
    var AllTypes = AppDomain.CurrentDomain.GetAssemblies().ToList()
                            .SelectMany(s => s.GetTypes())
                            .Where(p => BaseType.IsAssignableFrom(p));

    foreach (var typeToLoad in AllTypes)
        if (typeToLoad.IsInterface)
        var NewInstance = (IBroker) Activator.CreateInstance(typeToLoad);
        //var NewInstance = (IBroker)Activator.CreateInstance(Type.GetType(v.brokerType));
        NewInstance.Id = typeToLoad.ToString();


What's your thoughts on this?


Protected by WP Anti Spam