Access data from main application within a plugin in C#

有些话、适合烂在心里 提交于 2019-12-06 14:31:11

问题


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?


回答1:


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);



回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!