【问题标题】:Inject service into ViewModel with MVVM Light toolkit使用 MVVM Light 工具包将服务注入 ViewModel
【发布时间】:2017-01-07 04:55:25
【问题描述】:

我目前正在使用 WPF 和 MVVM Light 工具包制作应用程序。

我有这个视图模型:

public class MainViewModel : ViewModelBase
{
    // Instance of service which is used for sending email.
    private IEmailService _emailService;

    // Get/set instance of service which is used for sending email.
    public IEmailService EmailService
    {
        get
        {
            return _emailService;
        }
        set
        {
            Set("EmailService", ref _emailService, value);
        }
    }

    public MainViewModel()
    {
        _emailService = new ServiceLocator.Current.GetInstance<IEmailService>();
    }
}

电子邮件服务是一种处理发送/处理电子邮件的服务。当用户与屏幕上的元素交互时,会调用电子邮件服务(已在 ServiceLocator 中注册)

我想知道我的实现在 MVVM 设计模式下是否正确。有没有更好的方法将服务注入视图模型(当前的方法需要花费大量时间来声明初始化属性)

【问题讨论】:

    标签: wpf mvvm mvvm-light


    【解决方案1】:

    我想知道我的实现是否符合 MVVM 设计模式。

    依赖注入实际上与 MVVM 模式无关。 MVVM 是关于用户界面控件与其逻辑之间的关注点分离。依赖注入使您可以向类注入它需要的任何对象,而无需类自己创建这些对象。

    还有没有更好的方法将服务注入视图模型(当前的方法需要花费大量时间来声明初始化属性)

    如果视图模型类在不引用服务的情况下存在没有意义,则应使用构造函数依赖注入,而不是通过属性注入依赖。您可以在此处阅读更多相关信息:

    Dependency injection through constructors or property setters?

    使用您当前的实现,可以在没有服务的情况下使用视图模型类:

    MainViewModel vm = new MainViewModel();
    vm.EmailService = null;
    

    更好的实现应该是这样的:

    public class MainViewModel : ViewModelBase
    {
        // Instance of service which is used for sending email.
        private readonly IEmailService _emailService;
    
        public MainViewModel(IEmailService emailService = null)
        {
            _emailService = emailService ?? ServiceLocator.Current.GetInstance<IEmailService>();
    
            if(_emailService is null)
                throw new ArgumentNullException(nameof(emailService));
        }
    }
    

    这确保视图模型类始终具有对 IEmailService 的有效引用。它还可以在您构造对象时将其与 IEmailService 接口的任何实现一起注入。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-21
      • 2011-08-04
      • 2017-03-22
      • 1970-01-01
      • 2012-01-11
      相关资源
      最近更新 更多