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

推荐订阅源

酷 壳 – CoolShell
酷 壳 – CoolShell
H
Hacker News: Front Page
P
Palo Alto Networks Blog
T
ThreatConnect
Apple Machine Learning Research
Apple Machine Learning Research
博客园_首页
T
True Tiger Recordings
P
Privacy & Cybersecurity Law Blog
B
Blog
IT之家
IT之家
Last Week in AI
Last Week in AI
F
Full Disclosure
Hacker News: Ask HN
Hacker News: Ask HN
C
Comments on: Blog
Microsoft Azure Blog
Microsoft Azure Blog
C
Cybersecurity and Infrastructure Security Agency CISA
Microsoft Security Blog
Microsoft Security Blog
博客园 - 【当耐特】
N
News and Events Feed by Topic
NISL@THU
NISL@THU
腾讯CDC
雷峰网
雷峰网
Security Latest
Security Latest
李成银的技术随笔
M
Microsoft Research Blog - Microsoft Research
L
LangChain Blog
L
Lohrmann on Cybersecurity
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
C
Check Point Blog
Y
Y Combinator Blog
Recent Announcements
Recent Announcements
博客园 - Franky
N
News | PayPal Newsroom
V
V2EX
A
About on SuperTechFans
The Register - Security
The Register - Security
月光博客
月光博客
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Google Online Security Blog
Google Online Security Blog
MyScale Blog
MyScale Blog
Cisco Talos Blog
Cisco Talos Blog
Vercel News
Vercel News
WordPress大学
WordPress大学
C
Cyber Attacks, Cyber Crime and Cyber Security
The Hacker News
The Hacker News
IntelliJ IDEA : IntelliJ IDEA – the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
IntelliJ IDEA : IntelliJ IDEA – the Leading IDE for Professional Development in Java and Kotlin | The JetBrains Blog
爱范儿
爱范儿
A
Arctic Wolf
L
LINUX DO - 最新话题
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More

博客园 - aierong

CommunityToolkit.Mvvm系列文章导航 CommunityToolkit.Mvvm8.1 消息通知(4) CommunityToolkit.Mvvm8.1 viewmodel源生成器写法(3) - aierong 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联合打造))&lt;视频聊天,会议开发实例7&gt; Flex(flash)检测摄像头的3种状态(是否被占用,没安装摄像头,正常) - aierong - 博客园 Flex Air开发SQLite小结,SQLite开发工具及SQLite与Sql Server的语法差异汇总 开源Flex Air版免费激情美女视频聊天室,免费网络远程视频会议系统((Flex,Fms3联合打造))<视频聊天,会议开发实例6> - aierong 免费网络远程视频会议系统,免费美女多人视频聊天(附源码下载)(Flex和Fms3开发)&lt;视频聊天,会议开发实例5&gt; Flex组件的项目渲染器(ItemRenderer)使用总结 推荐几个Adobe Flex Builder 3的插件(代码格式化和fms服务器通讯文件(main.asc)编写) Flex组件开发总结-20090209 免费美女视频聊天,多人视频会议功能加强版本(Fms3和Flex开发(附源码))&lt;视频聊天,会议开发实例4&gt;
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