惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

量子位
Stack Overflow Blog
Stack Overflow Blog
人人都是产品经理
人人都是产品经理
The GitHub Blog
The GitHub Blog
Engineering at Meta
Engineering at Meta
Vercel News
Vercel News
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Y
Y Combinator Blog
The Cloudflare Blog
Last Week in AI
Last Week in AI
B
Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
T
Tailwind CSS Blog
V
Visual Studio Blog
博客园 - 三生石上(FineUI控件)
小众软件
小众软件
Google DeepMind News
Google DeepMind News
D
DataBreaches.Net
博客园 - 司徒正美
B
Blog RSS Feed
Microsoft Azure Blog
Microsoft Azure Blog
罗磊的独立博客
Hugging Face - Blog
Hugging Face - Blog
L
LangChain Blog

博客园 - aierong

CommunityToolkit.Mvvm系列文章导航 CommunityToolkit.Mvvm8.1 消息通知(4) CommunityToolkit.Mvvm8.1 viewmodel源生成器写法(3) wpf RelativeSource绑定 CommunityToolkit.Mvvm8.1 viewmodel使用-旧式写法(2) CommunityToolkit.Mvvm8.1 MVVM工具包安装引用指南(1) Jquery利用ajax调用asp.net webservice的各种数据类型(总结篇) 创建Windows服务(Windows Services)N种方式总结 .NET中对串口(COM)读写操作方式汇总 Sql Server2008 Transact-SQL 新兵器学习总结之-用户定义表类型和日期,时间数据类型 Air版免费视频成人聊天室,免费网络远程视频会议系统((Flex,Fms3联合打造))<视频聊天,会议开发实例7> Flex(flash)检测摄像头的3种状态(是否被占用,没安装摄像头,正常) - aierong - 博客园 Flex Air开发SQLite小结,SQLite开发工具及SQLite与Sql Server的语法差异汇总 开源Flex Air版免费激情美女视频聊天室,免费网络远程视频会议系统((Flex,Fms3联合打造))<视频聊天,会议开发实例6> 免费网络远程视频会议系统,免费美女多人视频聊天(附源码下载)(Flex和Fms3开发)<视频聊天,会议开发实例5> Flex组件的项目渲染器(ItemRenderer)使用总结 推荐几个Adobe Flex Builder 3的插件(代码格式化和fms服务器通讯文件(main.asc)编写) Flex组件开发总结-20090209 免费美女视频聊天,多人视频会议功能加强版本(Fms3和Flex开发(附源码))<视频聊天,会议开发实例4>
CommunityToolkit.Mvvm8.1 IOC依赖注入控制反转(5)
aierong · 2023-04-14 · via 博客园 - aierong

说明

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>();
    }
}

viewmodel中使用

vm的构造函数中注入服务即可

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>();

自我Demo地址:

https://github.com/aierong/WpfDemo/tree/main/WpfDemoNet6/IOCDemo

1