CommunityToolkit.Mvvm8.1 IOC依赖注入控制反转(5)
说明
CommunityToolkit.Mvvm包不提供ioc功能,但是官方建议使用:Microsoft.Extensions.DependencyInjection使用IOC
安装
nuget:Microsoft.Extensions.DependencyInjection 包
接口和服务的定义实现
public interface IBill
{
bool IsExistId ( string name );
string GetData ( string name );
}
public class BillService : IBill
{
public string GetData ( string name )
{
return string.Format( "name:{0}" , name );
}
public bool IsExistId ( string name )
{
return name == "qq";
}
}
App.xaml.cs注册
public partial class App : Application
{
/// <summary>
/// Gets the current <see cref="App"/> instance in use
/// </summary>
public new static App Current => ( App ) Application.Current;
/// <summary>
/// Gets the <see cref="IServiceProvider"/> instance to resolve application services.
/// </summary>
public IServiceProvider Services
{
get;
}
public App ()
{
Services = ConfigureServices();
this.InitializeComponent();
}
private static IServiceProvider ConfigureServices ()
{
var services = new ServiceCollection();
// 注册Services
services.AddSingleton<IOCDemo.Service.Repository.IBill , IOCDemo.Service.Repository.BillService>();
services.AddSingleton<IOCDemo.Service.Service.IBill , IOCDemo.Service.Service.BillService>();
//services.AddSingleton<ISettingsService , SettingsService>();
// 注册Viewmodels
// 不是每个Viewmodels都得来AddTransient,如果Viewmodels不需要ioc,可以不用这里注册
services.AddTransient<IOCDemo.ViewModels.WindowViewModel1>();
return services.BuildServiceProvider();
}
}
view中使用
原有的view与viewmodel的绑定方式改变如下:
public partial class Window1 : Window
{
public Window1 ()
{
InitializeComponent();
// this.DataContext = new WindowViewModel1(); 这样不可以使用了,请用App.Current.Services.GetService
this.DataContext = App.Current.Services.GetService<WindowViewModel1>();
//代码任何处,都可以使用App.Current.Services.GetService获取到服务
//IFilesService filesService = App.Current.Services.GetService<IFilesService>();
}
}
readonly Service.Service.IBill _IBill;
public WindowViewModel1 ( Service.Service.IBill iBill )
{
this._IBill = iBill;
}
[RelayCommand( CanExecute = nameof( CanButton ) )]
void ButtonClick ()
{
//点击按钮,修改标题
if ( this._IBill.IsExistId( Title ) )
{
Title = "qq" + this._IBill.GetData( Title );
}
else
{
Title = "qq";
}
}
this.DataContext = App.Current.Services.GetService<WindowViewModel1>();
//代码任何处,都可以使用App.Current.Services.GetService获取到服务
IFilesService filesService = App.Current.Services.GetService<IFilesService>();
1
我的系列文章
A.Sql Server2005 Transact-SQL 新兵器学习 B.MCAD学习
C.代码阅读总结
D.ASP.NET状态管理
E.DB(数据库)
F.WAP
G.WinForm
H.Flex
希望上面提到的知识对您有所提示,同时欢迎交流和指正
作者:aierong
出处:http://www.cnblogs.com/aierong
贴子以"现状"提供且没有任何担保,同时也没有授予任何权利!
本文版权归作者所有,欢迎转载!
原创技术文章和心得,转载注明出处!这也是对原创者的尊重!