Using dynamic class/properties at runtime to load configuration
I'm having a conundrum here, and I'm not even sure it's possible.
I'm developing a pluginbased application, where all the plugins will have access (read/write) to a shared configuration on the host application. There are easier ways of achieving the problem I'm presenting, but since this is a non-work related project, I'm free to play aroun开发者_如何转开发d :)
Let's say we have Plugin_A
that is inheriting a PluginBase
abstract class. The abstract class exposes a IConfiguration Config
property that can be accessed by the plugin to write to this shared configuration. The IConfiguration Config
is set properly by the host upon loading the plugin, to limit the available configuration that particular plugin will access.
What I would like to do is try and use the Dynamic keyword in C# 4.0 to seamlessly write the config-class.
in pseudo C# code here's what I would like to achieve
public class Plugin_A: PluginBase
{
public void DoSomethingWithConfig()
{
ShowAMessageBox(Config.SomeMessage);
Config.HasShownMessage = true;
}
}
Now - in this example I don't want to actually define the .SomeMessage
and .HasShownMessage
but rather have them be dynamic and returned when called upon.
It seems like a stretch, but is this at all possible?
I don't think you want to implement the IDynamicObject interface, I recommend you have Config inherit from DynamicObject instead. You'll want to override TryGetMember and TrySetMember at least for your example. TryInvokeMember will be necessary if you want to dynamically call methods. Implementing the whole interface is much more difficult.
So, your config class(es) will need to inherit DynamicObject and implement IConfiguration. You can then either declare the field as a dynamic item or as IConfiguration objects and cast them dynamic before you want to use their dynamic behaviors.
精彩评论