In one of the applications I am working on, there are two basic functionalities included: Create and Update.
However, there is a need sometimes to add custom code, so I thought of extending the code by allowing 3rd parties to write and embed their own code:
OnCreating OnCreated OnUpdating OnUpdated
Is there a way to enable the above across multiple assemblies? MEF might help here?
Thank you Regards
Thanks all for your replies.
Having such an interface means each external assembly has to implement that interface as needed. Then, my application's code, needs to loop through the currently running assemblies, detect all classes implementing that interface, and run their methods?
Does MEF fit here? I can export the implementation from external assemblies and import them inside my app?
Thank you Regards
You can't have partical classes accross assemblies because partial classes are a language feature, and not a CLR feature. The C# compiler merges all the partial classes into one real class, and that single class the the only thing left after compilation.
You have a couple of alternatives:
Your problem looks like it fits events best. The user can simply subscribe to them in the other assembly.
Regarding your MEF question, you could probably do something like the following to run methods from an interface:
var catalog = new DirectoryCatalog("bin");
var container = new CompositionContainer(catalog);
container.ComposeParts();
var plugins = container.GetExportedValues<IPlugin>();
foreach (IPlugin plugin in plugins)
{
plugin.OnCreating();
}
Or create an interface with events as Brian Mains suggested:
public interface IPlugin
{
event OnCreatingEventHandler OnCreating;
}
then the above code would be more like:
var catalog = new DirectoryCatalog("bin");
var container = new CompositionContainer(catalog);
container.ComposeParts();
var plugins = container.GetExportedValues<IPlugin>();
foreach (IPlugin plugin in plugins)
{
plugin.OnCreating += MyOnCreatingHandler;
}
I think I like the latter for the method names you specified. For my plugin work, I've created an interface similar to the following:
public interface IPlugin
{
void Setup();
void RegisterEntities();
void SeedFactoryData();
}
The RegisterEntities()
method extends the database schema at runtime, and the SeedFactoryData()
method adds any default data (eg. adding default user, pre-population of Cities table, etc.).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With