在这里检查我的答案。
http://codebetter.com/blogs/glenn.block/archive/2008/11/12/mvp-with-mef.aspx
编辑:(从链接中添加,以防止不被标记为低质量/ LOA)
1: using System.ComponentModel.Composition;
2: using System.Reflection;
3: using Microsoft.VisualStudio.TestTools.UnitTesting;
4:
5: namespace MVPwithMEF
6: {
7: /// <summary>
8: /// Summary description for MVPTriadFixture
9: /// </summary>
10: [TestClass]
11: public class MVPTriadFixture
12: {
13: [TestMethod]
14: public void MVPTriadShouldBeProperlyBuilt()
15: {
16: var catalog = new AttributedAssemblyPartCatalog(Assembly.GetExecutingAssembly());
17: var container = new CompositionContainer(catalog.CreateResolver());
18: var shell = container.GetExportedObject<Shell>();
19: Assert.IsNotNull(shell);
20: Assert.IsNotNull(shell.Presenter);
21: Assert.IsNotNull(shell.Presenter.View);
22: Assert.IsNotNull(shell.Presenter.Model);
23: }
24: }
25:
26: [Export]
27: public class Shell
28: {
29: private IPresenter _presenter = null;
30:
31: public IPresenter Presenter
32: {
33: get { return _presenter; }
34: }
35:
36: [ImportingConstructor]
37: public Shell(IPresenter presenter)
38: {
39: _presenter = presenter;
40: }
41: }
42:
43: public interface IModel
44: {
45: }
46:
47: [Export(typeof(IModel))]
48: public class Model : IModel
49: {
50:
51: }
52:
53: public interface IView
54: {
55: }
56:
57: [Export(typeof(IView))]
58: public class View : IView
59: {
60: }
61:
62: public interface IPresenter
63: {
64: IView View { get;}
65: IModel Model { get; }
66: }
67:
68: [Export(typeof(IPresenter))]
69: public class Presenter : IPresenter
70: {
71:
72: private IView _view;
73: private IModel _model;
74:
75: [ImportingConstructor]
76: public Presenter(IView view, IModel model)
77: {
78: _view = view;
79: _model = model;
80: }
81:
82: public IView View
83: {
84: get { return _view; }
85: }
86:
87: public IModel Model
88: {
89: get { return _model; }
90: }
91:
92: }
93: }
那么这里发生了什么?
Shell 被注入 Presenter。Presenter 被注入视图和模型。这里的一切都是单例,但不一定是。
我们两个示例之间的区别在于,Presenter 被注入到 shell 而不是 View 中。如果演示者正在创建视图,那么您不能只是先获取视图(就像他所做的那样),否则演示者将不会被创建。好吧,你可以做到,但你最终会把它砍成碎片。Cleaner 就是注入 Presenter 并让它暴露一个 IView。我们在 Prism 中做到了这一点,并且效果很好。