简体   繁体   中英

Is there a way to force a static method to execute?

Is there a way to force a static method to be executed in system initialization?

I'm developing a system all based in plugins. The core of the project will contain the system's state and will fire some events where plugins can hook up and create new features.

I want this plugin mechanism to be done transparently from plugins. All the plugin must do is implement an event of the system core and it should be executed correctly. The problem is for do that I need to execute some code on each plugin to hook the system core events. The solution I first thought was to declare some method in these plugins that will be executed when the assembly is loaded or something like that, but apparently static constructors are only executed when some reference of any of his fields is made; but in my design it can't be done: the plugins must stay invisible for the system core.

The plugins are essentially other classes or other projects.

Any thoughts?

Thanks.

I think the simplest thing to do is to define a common name for this method (like init()) and call it after you load each library.

Update, as said in comments

The point is to have a common, well defined, structure for the plugins, so which one you're loading at any given point does not matter, they're all the same from the core's point of view. It can just do something like

PluginType instantiatedPlugin=methodThatInstantiates(pluginClass);
instantiatedPlugin.init();

Then you can just loop through a list of plugins massively instantiating and initialising all of them.

If each plugin is a separated DLL, the list can be all the *.dll files in a plugins directory (add some security validation).

Or you could use Reflection to fetch all the plugins' classes. This is valid if the classes are inside the same binary or also after you loaded all DLLs.

You could do it easily if all the plugins are under the same namespace. See: Getting all types in a namespace via reflection

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM