首先,简单的问题。导出部分的MEF实例
当MEF(System.ComponentModel.Composition)创建零件的实例时,是否可以接收event
? 当发生这种情况时,我想反映创建的对象并连线各种属性。在Spring.Net中,可以使用IObjectPostProcessor
接口。
背景是我试图在MEF中实现Publisher/Subscriber模式。基本上,用户类做这样的:
class MyContoller
{
[Command("Print")]
public void Print() { ... }
[Command("PrintPreview")]
public void PrintPreview() { ... }
}
而且我想,当被myController的实例,并且有CommandAttribute
线了任何方法检测。
发布者(例如菜单项)将会执行Command.Get("Print").Fire()
来发布上述事件。
第二个问题
也许有在MEF的替代模式,我很想念!
我看过一些关于MEF, Prism and the Event Aggregate的贴子,但看起来相当复杂。
FYI
仅供参考,以下是Spring.Net实现原:
class CommandAttributeProcessor : IObjectPostProcessor
{
static ILog log = LogManager.GetLogger(typeof(CommandAttributeProcessor));
public object PostProcessAfterInitialization(object instance, string objectName)
{
foreach (MethodInfo methodInfo in instance.GetType().GetMethods())
{
foreach (CommandAttribute attr in methodInfo.GetCustomAttributes(typeof(CommandAttribute), true))
{
if (log.IsDebugEnabled)
log.Debug(String.Format("Binding method '{0}.{1}' to command '{2}'.", instance.GetType().Name, methodInfo.Name, attr.CommandName));
Command command = Command.Get(attr.CommandName);
command.Execute += (EventHandler) Delegate.CreateDelegate(typeof(EventHandler), instance, methodInfo);
}
}
return instance;
}
public object PostProcessBeforeInitialization(object instance, string name)
{
return instance;
}
}
我刚刚见过http://hammett.castleproject.org/index.php/2009/02/mef-exporting-and-importing-methods/也许就是这样。 –