gpt4 book ai didi

c# - PRISM + MEF -- 如何指定使用哪个导出?

转载 作者:太空狗 更新时间:2023-10-29 17:47:13 24 4
gpt4 key购买 nike

基本上,我如何指定要从哪些实现中进行选择?

FooService.cs:

public interface IFooService
{
Int32 GetFoo();
}

[Export(typeof(IFooService))]
public sealed class Foo100 : IFooService
{
public Int32 GetFoo()
{
return 100;
}
}


[Export(typeof(IFooService))]
public sealed class Foo200 : IFooService
{
public Int32 GetFoo()
{
return 200;
}
}

ClientViewModel.cs:

[Export()]
public class ClientViewModel : NotificationObject
{
[Import()]
private IFooService FooSvc { get; set; }

public Int32 FooNumber
{
get { return FooSvc.GetFoo(); }
}
}

Boostrapper.cs:

public sealed class ClientBootstrapper : MefBootstrapper
{
protected override void ConfigureAggregateCatalog()
{
base.ConfigureAggregateCatalog();

//Add the executing assembly to the catalog.
AggregateCatalog.Catalogs.Add(new AssemblyCatalog(Assembly.GetExecutingAssembly()));
}

protected override DependencyObject CreateShell()
{
return Container.GetExportedValue<ClientShell>();
}

protected override void InitializeShell()
{
base.InitializeShell();

Application.Current.MainWindow = (Window)Shell;
Application.Current.MainWindow.Show();
}
}

ClientShell.xaml.cs:

[Export()]
public partial class ClientShell : Window
{
[Import()]
public ClientViewModel ViewModel
{
get
{
return DataContext as ClientViewModel;
}
private set
{
DataContext = value;
}
}

public ClientShell()
{
InitializeComponent();
}
}

我不确定从这里去哪里设置我的应用程序以注入(inject)正确的应用程序(在这种情况下,我希望注入(inject) Foo100。我知道我可以让它们自己导出并指定一个 Foo100 IFooService,但这是正确的方法吗?

最佳答案

如果有多个导出与某个契约(Contract),那么您将不得不全部导入它们(通过声明一个集合类型的属性并在其上添加 ImportMany 属性)或制定契约(Contract)通过指定契约(Contract)名称更具体:

[Export("Foo100", typeof(IFooService))]
public sealed class Foo100 : IFooService
{
public Int32 GetFoo()
{
return 100;
}
}


[Export("Foo200", typeof(IFooService))]
public sealed class Foo200 : IFooService
{
public Int32 GetFoo()
{
return 200;
}
}

-

[Import("Foo100", typeof(IFooService)]
private IFooService FooSvc { get; set; }

关于c# - PRISM + MEF -- 如何指定使用哪个导出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5160329/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com