简体   繁体   中英

SimpleIoc issue within WPF MVVM light application

I have a wpf application using MVVM Light . I have two class and interface :

public interface ICrud{
//
}

public class CrudDAO : ICrud{
//
}

public class CrudEF : ICrud{
//
}

I have two viewmodels :

  public class CrudDAOVM {
       public  ICrud icrud;
       public CrudDAOVM (ICrud _icrud)
       {
        icrud = _icrud;
       }
                         }

    public class CrudEFVM {
       public  ICrud icrud;
       public CrudEFVM (ICrud _icrud)
        {
        icrud = _icrud;
        }
                          }

I'd like to use SimpleIoc to inject the depencies. So I added this code in the ViewModelLocator :

SimpleIoc.Default.Register<ICrud , CrudDAO >(); //I'd like to add the condition here
SimpleIoc.Default.Register<ICrud , CrudEF >();//I'd like to add the condition here

I'd like to add a condition specify that inside CrudVMDAO, the implementation of ICrud is CrudDAO, and inside CrudVMEF, the implementation of ICrud is CrudEF

Is it possible to do this using SimpleIoc ?

If you want to register several implementations, you can add a key to differentiate them during registration as shown below.

SimpleIoc.Default.Register<ICrud>(() => new CrudDAO(), "CrudDAO");
SimpleIoc.Default.Register<ICrud>(() => new CrudEF(), "CrudEF");

Inside CrudVMDAO:

SimpleIoc.Default.GetInstance<ICrud>("CrudDAO");

Inside CrudVMEF:

SimpleIoc.Default.GetInstance<ICrud>("CrudEF");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM