Singleton中的构造函数DI

时间:2014-08-11 16:59:21

标签: c# windows-phone-8 mvvm dependency-injection

我需要在Map control中使用ViewModel(这与MVVM相矛盾,我不确定需要什么,但这是另一个问题)。

我使用Dependency Injection模式,实现构造函数注入

IMapService接口

public interface IMapService
{
     Microsoft.Phone.Maps.Controls.Map Map
     {
        get;           
     }
}

ViewModelLocator

public class ViewModelLocator
    {
        public MeetingsViewModel Meetings
        {
            get { return ServiceLocator.Current.GetInstance<MeetingsViewModel>(); }
        }    

        static ViewModelLocator()
        {
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);            
            SimpleIoc.Default.Register<MeetingsViewModel>();
        }
    }

视图模型

public class MeetingsViewModel   
{
    private ObservableCollection<MeetingViewModel> _meetings;
    public ObservableCollection<MeetingViewModel> Meetings
    {
        get { return _meetings; }
        set
        {
           _meetings = value;
           NotifyPropertyChanged("Meetings");
        }
    }    

    private readonly IMapService _mapService;


    public MeetingsViewModel(IMapService mapService)
    {
        _mapService = mapService;
        _mapService.Map.ResolveCompleted += (s, e) => ClusterHelper.RenderPins(Meetings, _mapService.Map);  //render pushpins 
    }

    //...
}

查看

public partial class Meeting : PhoneApplicationPage, IMapService
    {
        private ViewModelLocator viewModelLocator = new ViewModelLocator();

        public Meeting()
        {
            InitializeComponent();      
            SimpleIoc.Default.Register<IMapService>(() => this);
            this.DataContext = viewModelLocator.Meetings;
        }

        public Microsoft.Phone.Maps.Controls.Map Map
        {
            get { return MyMap; } // return Map control
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
           base.OnNavigatedFrom(e);
           SimpleIoc.Default.Unregister<IMapService>();               
        }
    }

但是,如果我Singleton ViewModel Instance属性中的构造函数注入更好?

static MeetingsViewModel instance = null;

public static MeetingsViewModel Instance
{
   get
   {
       lock (padlock)
       {
          if (instance == null)
          {
              instance = new MeetingsViewModel(); 
          }
          return instance;
       }
   }
}

ViewModelLocator

public class ViewModelLocator
    {
        public MeetingsViewModel Meetings
        {
            get { return ServiceLocator.Current.GetInstance<MeetingsViewModel>(); }
        }    

        static ViewModelLocator()
        {
            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);            
            SimpleIoc.Default.Register<MeetingsViewModel>(() => MeetingsViewModel.Instance);
        }
    }

0 个答案:

没有答案