[英]How do I populate a MEF plugin with data that is not hard coded into the assembly?
我正在开发一个可以与各种硬件通信的程序。 由于它传达和控制的物品的性质各异,因此我需要为每个不同的硬件使用不同的“驱动程序”。 这使我认为MEF是将那些驱动程序制作为即使在产品发布后也可以添加的插件的好方法。
我看了很多有关如何使用MEF的示例,但是我一直无法找到答案的问题是如何用外部数据(例如,来自数据库)填充MEF插件。 我可以找到的所有示例都将“数据”硬编码到了程序集中,例如以下示例:
[Export( typeof( IRule ) )]
public class RuleInstance : IRule
{
public void DoIt() {}
public string Name
{
get { return "Rule Instance 3"; }
}
public string Version
{
get { return "1.1.0.0"; }
}
public string Description
{
get { return "Some Rule Instance"; }
}
}
如果我希望名称,版本和描述来自数据库怎么办? 我如何告诉MEF在哪里获取该信息?
我可能会错过一些非常明显的东西,但我不知道它是什么。
通过属性加载插件后,您必须将信息传递给插件:
[Export( typeof( IRule ) )]
public class RuleInstance : IRule
{
puliic void DoIt()
{ }
public string Name { get; set; }
}
public class Program
{
[Import(typeof( IRule ))]
public IRule instance { get; set; }
public void Run()
{
// Load the assemblies here
instance.Name = "Rule Instance 3";
}
}
或者插件可以通过主机接口请求变量。 您可以通过属性或通过构造函数参数传递IHost实例,但是使用MEF构造函数参数并不简单。 这是通过属性:
[Export( typeof( IRule ) )]
public class RuleInstance : IRule
{
puliic void DoIt()
{ }
public void Initialise()
{
// Load our name from the host, this cannot be done in the constructor
string name = Host.GetName(/* some parameters? */)
}
public IHost Host { get; set; }
public string Name { get; set; }
}
public interface IHost
{
string GetName(/* some parameters? */);
}
public class Program : IHost
{
[Import(typeof( IRule ))]
public IRule instance { get; set; }
public void Run()
{
// Load the assemblies here
// Make sure the plugins know where the host is...
instance.Host = this;
}
}
您还可以“导出”数据库接口,并将其“导入”到需要数据库访问的任何插件中。
您始终可以导出单个值(通过合同名称),这是一个示例:
public class Configuration
{
[Export("SomeValue")]
public string SomeValue
{
get { /* return value from database perhaps? */ }
}
}
[Export(typeof(IRule))]
public class RuleInstance : IRule
{
[Import("SomeValue")]
public string SomeValue { get; private set; }
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.