|
Create Extensible .NET Apps
Implement plug-ins to extend and customize your Windows Forms applications.
by Francesco Balena
April 15, 2005
Technology Toolbox: VB.NET
It’s nice to create applications that you can customize easily for different customers. At the same time, you don’t want to disperse hundreds of If statements and other conditional blocks just to account for each and every possible user. In fact, you shouldn’t do this, for at least two reasons: First, it would force you to recompile and redeploy your executables for each minor change; second, it would make source code maintenance a nightmare.
Creating customized applications means you must plan well in advance the ways in which you want your application to be extensible. For example, you must decide whether an extension can change the structure of existing forms or replace them with a completely new form, or both. You must also establish whether an extension can intervene during operations, such as when loading and saving data, and so forth.
An effective approach to creating extensible and customizable apps is to use plug-in DLLs that leverage many programming techniques such as custom attributes, reflection, and interfaces. Following the guidelines in this article will let you change the appearance and the behavior of a WinForms program by simply asking your customers to copy a DLL into a given directory under the app’s directory tree.
An extensible app consists of three types of executable files: the main app’s EXE file, the ExtensibilityLib.dll file, and zero or more plug-in DLLs (see Figure 1). The ExtensibilityLib.dll defines the all-important FormExtender custom attribute, which you use to mark a plug-in class that extends a given form in the main app. This DLL also defines the FormExtenderManager type, which exposes methods the main app and your plug-ins use.
The mechanism works roughly like this: When the main application creates a new form, it should pass the form object to the FormExtenderManager.NotifyFormCreation method. The first time this method is invoked, it calls the InitializePlugins method, which scans all the DLLs stored in the application’s main directory and keeps track of all the types that are marked with a FormExtender attribute.
The NotifyFormCreation method creates an instance of all the types (stored in the plug-in DLLs) that want to extend the form currently shown. The code in the plug-in assembly receives the instance of the form being created, so it can change its properties, add or remove controls, create event handlers for existing controls, and so on. For example, assume you want to create an extremely simple plug-in that receives the form object in the class constructor and changes its background color to red:
<ExtensibilityLib.FormExtender(_
"MainApp.Form1")> _
Public Class Form1_Extender
Sub New(ByVal frm As Form)
frm.BackColor = Color.Red
End Sub
End Class
Back to top
|