导入的MEF问题

时间:2010-12-14 15:08:46

标签: wpf mef

我有导入shell-view-model到view-model类的问题,我使用MEF。

Shell-view-model:

namespace Spirit.ViewModels
{
    using Caliburn.Micro;
    using System.ComponentModel.Composition;

    public interface IShellViewModel
    {
        void ShowLogOnView();
        void ShowMessengerView();
    }

    [Export(typeof(IShellViewModel))]
    public class ShellViewModel : Conductor<IScreen>, IShellViewModel
    {
        public ShellViewModel()
        {
            ShowLogOnView();
        }

        public void ShowLogOnView()
        {
            ActivateItem(new LogOnViewModel());
        }

        public void ShowMessengerView()
        {
            ActivateItem(new LogOnViewModel());
        }
    }

}

我在view-model类中需要这个类导入:

[Export]
public class LogOnViewModel : Screen, IDataErrorInfo
{

    [Import]
    private IShellViewModel _shellViewModel;


    public void LogOn(string nick, string password)
    {
        IMessengerViewModel vm = IoC.Get<MessengerViewModel>();
        _shellViewModel.ShowMessengerView();
    }
}

问题是在初始化之后是变量_shellViewModel null。

我的bootstraper看起来像这样:

  public class MefBootStrapper : Bootstrapper<IShellViewModel>
  {

  }

我的解决方案:

我创建了接口程序集,并在外部服务dll和wpf app中引用此程序集。

在bootstraper中,我用反射加载这个程序集:

    var catalog =
    new AggregateCatalog(
        AssemblySource.Instance.Select(x => new AssemblyCatalog(x)).OfType<ComposablePartCatalog>());

catalog.Catalogs.Add(
    new AssemblyCatalog(string.Format(
        CultureInfo.InvariantCulture, "{0}{1}", System.IO.Directory.GetCurrentDirectory(), @"\Pokec_Toolkit.dll")));

_container = new CompositionContainer(catalog);

比我创建指挥班:

public interface IShellViewModel
{
    void ShowLogOnView();
    void ShowMessengerView();
}

[Export(typeof(IShellViewModel))]
public class ShellViewModel : Conductor<IScreen>, IShellViewModel
{
    public ShellViewModel()
    {
        ShowLogOnView();
    }

    public void ShowLogOnView()
    {
        ActivateItem(IoC.Get<LogOnViewModel>());
    }

    public void ShowMessengerView()
    {
        ActivateItem(IoC.Get<MessengerViewModel>());
    }
}

在视图模型中我有这个:

  [Export]
    public class LogOnViewModel : Screen, IDataErrorInfo, ILogOnViewModel
    {

        [Import]
        private IShellViewModel _shellViewModel;

        [Import]
        private IPokecConnection _pokecConn;

//this method is bind on event click of button
        public void LogOn(string nick, string password)
        {
            //SHOW NEW WIEW
           _shellViewModel.ShowMessengerView();
        }
    }

0 个答案:

没有答案