I am using this approach to make my C#-application extensible for other developers:
Creating a simple plugin mechanism
It works just fine but only in "one direction" which means that the developer who writes a new plugin can define methods and variables within the plugin and those will be imported to my application.
So my question is now: How can i access already existing data from my main application (e.g. a variable "string test") within the plugin?
You need to create an "SDK" for your application which is available to your plugin writers. This should contain interfaces for anything you want to make externally accessible.
e.g.
MyAppSdk.dll
public interface IMyApplicationContext {
string SomeData { get; set; }
IMyAppService SomeService { get; set; }
}
public interface IPlugin {
void Do(IMyApplicationContext context)
}
Plugin
public class MyPlugin : IPlugin {
public void Do(IMyApplicationContext context) {
context.SomeService.DoAThing();
System.Windows.MessageBox.Show(context.SomeData);
}
}
Application
context = GetApplicationContext();
plugin.Do(context);
There are several ways.
You could create a Dictionary<string, object>
where every module has access to set or get data. You should write some logic to access that dictionary. For example a T GetData<T>(string key)
method to bring a bit type safety into it.
You could use an event system like EventAggregator
in the PRISM framework to enable communication between your modules as well.
But be aware hat this will make your modules dependant from each other. That's why you should handle e.g. if data is not available from another module.
来源:https://stackoverflow.com/questions/45143052/access-data-from-main-application-within-a-plugin-in-c-sharp