基本上,我如何指定要从哪些实现中进行选择?
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/