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

推荐订阅源

N
News and Events Feed by Topic
T
The Exploit Database - CXSecurity.com
P
Palo Alto Networks Blog
T
Threat Research - Cisco Blogs
Cloudbric
Cloudbric
Recent Commits to openclaw:main
Recent Commits to openclaw:main
I
Intezer
Attack and Defense Labs
Attack and Defense Labs
P
Privacy International News Feed
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
L
Lohrmann on Cybersecurity
C
Cybersecurity and Infrastructure Security Agency CISA
V2EX - 技术
V2EX - 技术
AWS News Blog
AWS News Blog
O
OpenAI News
L
LINUX DO - 最新话题
N
News | PayPal Newsroom
PCI Perspectives
PCI Perspectives
www.infosecurity-magazine.com
www.infosecurity-magazine.com
T
Troy Hunt's Blog
Latest news
Latest news
D
Darknet – Hacking Tools, Hacker News & Cyber Security
A
Arctic Wolf
Spread Privacy
Spread Privacy
G
GRAHAM CLULEY
T
Tor Project blog
博客园_首页
Know Your Adversary
Know Your Adversary
有赞技术团队
有赞技术团队
S
Secure Thoughts
美团技术团队
Apple Machine Learning Research
Apple Machine Learning Research
爱范儿
爱范儿
T
Tailwind CSS Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
V
Visual Studio Blog
J
Java Code Geeks
Cisco Talos Blog
Cisco Talos Blog
Schneier on Security
Schneier on Security
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
S
Security Affairs
Jina AI
Jina AI
人人都是产品经理
人人都是产品经理
雷峰网
雷峰网
宝玉的分享
宝玉的分享
量子位
Last Week in AI
Last Week in AI
月光博客
月光博客
罗磊的独立博客
S
SegmentFault 最新的问题

博客园 - 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