Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

c# - how to use MVVMLight SimpleIoc?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

SimpleIoc crib sheet:

1) You register all your interfaces and objects in the ViewModelLocator

class ViewModelLocator 
{ 
    static ViewModelLocator() 
    {         
        ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);          
        if (ViewModelBase.IsInDesignModeStatic) 
        {              
            SimpleIoc.Default.Register<IDataService, Design.DesignDataService>();          
        }          
        else         
        {              
            SimpleIoc.Default.Register<IDataService, DataService>();          
        }          
        SimpleIoc.Default.Register<MainViewModel>();                  
        SimpleIoc.Default.Register<SecondViewModel>(); 
    }      


    public MainViewModel Main 
    {  
        get  
        {      
            return ServiceLocator.Current.GetInstance<MainViewModel>();  
        } 
    }
} 

2) Every object is a singleton by default. To resolve an object so that it's not a singleton you need to pass a unique value to the GetInstance call:

SimpleIoc.Default.GetInstance<MainViewModel>(Guid.NewGuid().ToString());

3) To register a class against an interface:

SimpleIoc.Default.Register<IDataService, Design.DesignDataService>();  

4) To register a concrete object against an interface:

SimpleIoc.Default.Register<IDataService>(myObject);     

5) To register a concrete type:

SimpleIoc.Default.Register<MainViewModel>();   

6) To resolve an object from an interface:

SimpleIoc.Default.GetInstance<IDataService>();

7) To resolve an object directly (does buildup and dependency resolution):

SimpleIoc.Default.GetInstance<MainViewModel>();

8) MVVM makes doing design-time data really easy:

if (ViewModelBase.IsInDesignModeStatic) 
{              
    SimpleIoc.Default.Register<IDataService, Design.DesignDataService>();          
}          
else         
{              
    SimpleIoc.Default.Register<IDataService, DataService>();          
}  

If you're in design-time mode it will automatically register your design-time services, making it really easy to have data in your viewmodels and views when working in the VS designer.

Hope this helps.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...