I try to use dependency injection to inject service into view model. try this code
ViewModelLocator
public class ViewModelLocator
{
public static MainViewModel _main;
static ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
SimpleIoc.Default.Register<IAccountService, AccountService>();
SimpleIoc.Default.Register<MainViewModel>();
SimpleIoc.Default.Register<LoginViewModel>();
}
/// <summary>
/// Gets the Main property.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
"CA1822:MarkMembersAsStatic",
Justification = "This non-static member is needed for data binding purposes.")]
public IMainViewModel Main
{
get
{
return ServiceLocator.Current.GetInstance<IMainViewModel>();
}
}
/// <summary>
/// Gets the Main property.
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
"CA1822:MarkMembersAsStatic",
Justification = "This non-static member is needed for data binding purposes.")]
public LoginViewModel Login
{
get
{
return ServiceLocator.Current.GetInstance<LoginViewModel>();
}
}
/// <summary>
/// Cleans up all the resources.
/// </summary>
public static void Cleanup()
{
}
}
MainViewModel
public interface IMainViewModel
{
}
public class MainViewModel : ViewModelBase
{
private readonly IAccountService _accountService;
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel(IAccountService accountService)
{
_accountService = accountService;
}
}
my LoginViewModel
public interface ILoginViewModel
{
ICommand Authorize { get; set; }
}
public class LoginViewModel : ViewModelBase, IMainViewModel
{
private IAccountService _accountService;
public LoginViewModel(IAccountService _accountService)
{
this._accountService = _accountService;
Authorize = new RelayCommand(() => CheckAuthorized(), () => true);
}
public ICommand Authorize { get; private set; }
}
and this my LoginView
public partial class Login : UserControl
{
ILoginViewModel _loginViewModel;
public Login(ILoginViewModel _loginViewModel)
{
this._loginViewModel = _loginViewModel;
InitializeComponent();
DataContext = _loginViewModel;
}
}
my question is, when i try to inject in my View, the object reference is null,
how can i use DI in mvvm light?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…