2

我已经配置了容器:

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?**
    }
}
4

1 回答 1

3

你这样做的方式与你MainWindowCreateShell方法覆盖中获得一个实例的方式相同。您所要做的就是调用Container.GetExportedValue<T>(),它允许您直接获取实例。然而,如果你想注入一个类型,为了更松散的耦合,你需要一个带有[ImportingConstructor]依赖于该类型(或者最好是一个接口)的属性的构造函数,或者一个具有属性的该类型的[Import]属性。

确保通过使用[Export]属性装饰类来导出类型,并将程序集添加到AggregateCatalog.

希望这可以帮助 ;)

于 2011-03-01T12:23:59.097 回答