How do I create instances of my classes in Prism4 MEF?
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)
开发者_Python百科{
_event = @event;
_uiManager = uiManager;
}
private void Foo()
{
var vm = **How create instance of desired type here?**
}
}
You do that the same way you got an instance of MainWindow
in the CreateShell
method override. All you have to do is call Container.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 the AggregateCatalog
.
Hope this helps ;)
精彩评论