I have a dictionary of registered types.
Dictionary<Type, Type> knownTypes = new Dictionary<Type, Type>() {
{ typeof(IAccountsPlugin), typeof(DbTypeA) },
{ typeof(IShortcodePlugin), typeof(DbTypeB) }
};
I need to test if an object implements a specific interface as a key, and if so instantiate the counterpart value.
public Plugin FindDbPlugin(object pluginOnDisk)
{
Type found;
Type current = type.GetType();
// the below doesn't work - need a routine that matches against a graph of implemented interfaces
knownTypes.TryGetValue(current, out found); /
if (found != null)
{
return (Plugin)Activator.CreateInstance(found);
}
}
All types that will be created (in this case DbTypeA, DbTypeB and so forth) will only ever derive from type Plugin.
The object that is passed in may be inherited from one of the types we are trying to match (i.e. IAccountsPlugin) by several generations of inheritance. This is why I cannot do pluginOnDisk.GetType().
Is there a way to test if an object implements a type, and then create the new instance of that type, with a dictionary lookup rather than brute forcing and testing typeof in a long loop?
Change this method to be generic, and specify the type of the object you are looking for:
Example: