views:

219

answers:

2

I have implemented a 'plugin' system where my application creates classes that implement an interface at runtime to allow pluggable functionality.

I am achieving this by using Activator.CreateInstance on all classes that implement the specified interface within the plugin assembly.

At the current time I am only using one implementation of the class, and for it I have two constructor arguments, and have included those in the Activator.CreateInstance call:

 instanceList.Add((Foo)Activator.CreateInstance(_TypeList[typeKey], new object[] { arg1, arg2 }));

I realise this may cause problems later if an implementation is added that does not use this constructor signature. What is the best situation to handle this.

Explicitly say via documentation that constructors need to use this signature, and then surround it in a try/catch?

Or would there be a way to invoke whatever constructor a class has? bearing in mind I would have to match up constructor arguments somehow.

Or... avoiding constructor arguments by putting the arguments in a static class as static propertys?

+1  A: 

Firstly I would refactor the code to abstract the construction to say a factory class. Then the strategy used by the factory can decide the best way (if differing) and what to do in case of errors - such as missing constructor. You can use generics to make the interfaces as strongly or loosely typed as you need.

I'd stick with Activator though. We've done a lot of work with this kind of construction and its bought us a lot of things including late binding based on types discovered at runtime, singleton, type aliasing, custom security etc.

Preet Sangha
+1  A: 

I would require all plug-ins to have a constructor without parameters and add an initialize method to the interface, with some general arguments.

There is no way to know which arguments all possible implemetations of the plug-in require.

pb