如何在 Prism4 MEF 中创建我的类的实例?
我已配置容器:
public class MyBootstrapper : MefBootstrapper
{
protected override void ConfigureAggregateCatalog()
{
AggregateCatalog.Catalogs.Add(xxx.Assembly));
// other assemblies
}
protected override void InitializeShell()
{
base.InitializeShell();
Application.Current.MainWindow = (MainWindow)Shell;
Application.Current.MainWindow.Show();
}
protected override DependencyObject CreateShell()
{
return Container.GetExportedValue<MainWindow>();
}
}
如何在模块中创建类型 T 的实例?类型 T 在程序集中的某处定义,由 MEF 配置。
我需要这样的:
var myType = XXXX.Resolve<T>();
UPD1。 我的模块
[ModuleExport(typeof(CatalogModule))]
public class CatalogModule : IModule
{
private readonly IEventAggregator _event;
private readonly IUIManager _uiManager;
[ImportingConstructor]
public CatalogModule(IEventAggregator @event, IUIManager uiManager)
{
_event = @event;
_uiManager = uiManager;
}
private void Foo()
{
var vm = **How create instance of desired type here?**
}
}
I have configured container:
public class MyBootstrapper : MefBootstrapper
{
protected override void ConfigureAggregateCatalog()
{
AggregateCatalog.Catalogs.Add(xxx.Assembly));
// other assemblies
}
protected override void InitializeShell()
{
base.InitializeShell();
Application.Current.MainWindow = (MainWindow)Shell;
Application.Current.MainWindow.Show();
}
protected override DependencyObject CreateShell()
{
return Container.GetExportedValue<MainWindow>();
}
}
How can I create instance of my type T in module? Type T is defined somewhere in assemblies, that are configured by MEF.
I need some like this:
var myType = XXXX.Resolve<T>();
UPD1.
MyModule
[ModuleExport(typeof(CatalogModule))]
public class CatalogModule : IModule
{
private readonly IEventAggregator _event;
private readonly IUIManager _uiManager;
[ImportingConstructor]
public CatalogModule(IEventAggregator @event, IUIManager uiManager)
{
_event = @event;
_uiManager = uiManager;
}
private void Foo()
{
var vm = **How create instance of desired type here?**
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
执行此操作的方式与在
CreateShell
方法重写中获取MainWindow
实例的方式相同。您所要做的就是调用Container.GetExportedValue()
,它允许您直接获取实例。但是,如果您想要注入类型,为了实现更松散的耦合,您需要一个带有[ImportingConstructor]
属性的构造函数,该属性取决于该类型(或者最好是接口),或者具有[Import]
属性的该类型的属性。确保通过使用
[Export]
属性修饰类来导出类型,并将程序集添加到AggregateCatalog
中。希望这有帮助;)
You do that the same way you got an instance of
MainWindow
in theCreateShell
method override. All you have to do is callContainer.GetExportedValue<T>()
, which allows you to get an instance directly. If, however, you want to have a type injected, for more loose coupling, you need to have a constructor with and[ImportingConstructor]
attribute that depends on that type (or preferably, an Interface), or a property of that type with an[Import]
attribute.Make sure that you have your type exported, by decorating the class with a
[Export]
attribute, and that the assembly is added to theAggregateCatalog
.Hope this helps ;)