Mvvm - How to get instance key in SimpleIoC

I use mvvm light SimpleIoC in a Xamarin project and use the instance key to get some presentation model.

SimpleIoc.Default.GetInstance<ContextViewModel>("contextIdentifier");

Is there a way to get this instance key in the instance itself, like other dependencies, in the constructor?

I know that I can create and set a custom property on mine ContextViewModel, but since my class needs this value to work, I don’t like the idea that I can get a “non-working instance” of this view model.

Edit with additional information to explain why I want my ViewModel instance to know about its identifier:

This is the Xamarin.iOS application ( ViewControllercreated by the storyboard).

In my application, I have several instances of the same view controller (and in the same one UITabBarController), and therefore I need a different ViewModel instance for each instance of the view controller.

Since my ViewModel needs an identifier to get some data from the database, I thought I would use this identifier as well as the instance identifier.

I can make it work by getting an instance of ViewModel in the ViewDidLoad () method of my view controller and name some Setters on it, but I don't like it (maybe I'm wrong :)) because in my Mind, IoC should only return operating instances (without the need for multi-line dialing).

Sincerely.

+4
2

, , , , , ViewController, id ServiceLocator.

public interface IIdentifiableViewModel
{
    /// <summary>
    /// Gets or sets the instance key.
    /// </summary>
    /// <value>The instance key.</value>
    string InstanceKey { get; set; }
}

ServiceLocator:

public class ServiceLocator
{
    /// <summary>
    /// Gets the view model instance by key and pass it to the InstanceKey property
    /// </summary>
    /// <returns>The view model by key.</returns>
    /// <param name="key">Key.</param>
    /// <typeparam name="T">The 1st type parameter.</typeparam>
    public T GetViewModelByKey<T>(string key) where T : IIdentifiableViewModel
    {
        var vm = ServiceLocator.Current.GetInstance<T>(key);
        ((IIdentifiableViewModel)vm).InstanceKey = key;

        return vm;
    }

, .

+1

, . SimpleIOC. ViewModel InstanceID.

var viewModel = SimpleIoc.Default.GetInstance<MyViewModel>("contextIdentifier");
viewModel.ID = "contextIdentifier";

public class MyViewModel : ViewModelBase
{
  public string ID { get; set; }
}
+1

Source: https://habr.com/ru/post/1684286/


All Articles