How to allow external add-ins to be easily interfaced with .net 3.0 application?
I want to expose few methods开发者_开发知识库 (or interfaces) from my ERP application and my clients want to add their own modules to achieve some functionality. For instance, we can write our own add-in modules to visual studio.
Kindly let me know how to achieve this.
You'll probably want to look at something like MEF or the Composite UI Application Block. If you want to "do it yourself", the basics are:
- Define an interface that add-ins can implement
- Specify a folder that your application will search for add-ins
- Have your application enumerate each assembly in the folder specified and
- Use reflection to load each type from the assembly
- Check to see if the type implements the interface you specified in (1)
- Instantiate each type that implements the interface and call a "register" method that the interface defines
Having done this before I can't not warn you that there are problems and pit-falls in getting this right. If you can use something like MEF to do the "heavy lifting" for you, go for it as it makes life a lot easier - far better to have someone at Microsoft write your add-in system for you! =)
My quick suggestion:
- Expose interface(s) with a possible Load() hook/callback
- Define module folder
- Attempt to Load() each assembly in module folder
- Once Load()ed, use functionality as needed.
I totally agree with Rob, but let me extend Rob's answer a little.
MEF is quite heavy and verbose. I mean you have to implement a lot of special classes derived from MEF's interfaces, and in most cases they will be just a standard realisation of interface, no special logic. So if you don't need all this heavy functionality and want some lightweight solution - implement your own following steps in Rob's answer. I talk about previous versions of MEF, I don't know whether the last version is more convenient to use than previous.
If you decide to go with implementing your own plug-ins architecture, I heavily advice you to consider using Microsoft patterns and practices Unity for plug-ins instantiation. This will eliminate headache about how to initialize plug-ins, because Unity will take care of dependencies, required by plug-ins via plug-ins constructors. You just need to declare interfaces, that you want to expose as API. And plug-ins developers should only reference these interfaces in plug-ins constructors. Unity is quite lightweight and easy to use.
精彩评论