CommunityToolkit.Mvvm8.1 IOC依賴註入控制反轉(5)

来源:https://www.cnblogs.com/aierong/archive/2023/04/14/17318614.html
-Advertisement-
Play Games

本系列文章導航 https://www.cnblogs.com/aierong/p/17300066.html https://github.com/aierong/WpfDemo (自我Demo地址) 希望提到的知識對您有所提示,同時歡迎交流和指正 作者:aierong出處:https://www ...


 

本系列文章導航
  1. https://www.cnblogs.com/aierong/p/17300066.html
  2. https://github.com/aierong/WpfDemo (自我Demo地址)


希望提到的知識對您有所提示,同時歡迎交流和指正
作者:aierong
出處:https://www.cnblogs.com/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

 

我的系列文章
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
貼子以"現狀"提供且沒有任何擔保,同時也沒有授予任何權利!
本文版權歸作者所有,歡迎轉載!
原創技術文章和心得,轉載註明出處!這也是對原創者的尊重!


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 簡述 GDB, the GNU Project debugger, allows you to see what is going on 'inside' another program while it executes -- or what another program was doing a ...
  • token驗證 什麼是token?我相信很多開發者都或多或少聽過基於 token 的用戶鑒權和基於 session 的用戶鑒權,而今天說的 token 驗證就是第一種了。token 的意思是“令牌”,是用戶第一次登錄伺服器返回的,它能讓用戶不需要提交賬戶和密碼就能進行伺服器驗證身份,它是被放在請求頭 ...
  • @RequstBody、@RequstParam 這些註解是不是很熟悉?我們在開發Controller介面時經常會用到此類參數註解,那這些註解的作用是什麼?我們真的瞭解嗎? ...
  • Tokio 無疑是 Rust 世界中最優秀的非同步Runtime實現。非阻塞的特性帶來了優異的性能,但是在實際的開發中我們往往需要在某些情況下阻塞任務來實現某些功能。 ...
  • Redis 環境 redis 安裝、配置,啟動:(此處以雲伺服器上進行說明) 下載地址:https://redis.io/download/ 下載後上傳到雲伺服器上,如 /usr/local 中 gcc 環境安裝:yum install -y gcc-c++ 解壓:tar -zxvf xxx 進入解 ...
  • 輸入兩個整數序列,第一個序列表示棧的壓入順序,請判斷第二個序列是否為該棧的彈出順序。假設壓入棧的所有數字均不相等。例如,序列 {1,2,3,4,5} 是某棧的壓棧序列,序列 {4,5,3,2,1} 是該壓棧序列對應的一個彈出序列,但 {4,3,5,1,2} 就不可能是該壓棧序列的彈出序列。 示例 1 ...
  • JVM記憶體分配 先瞭解下JVM中的記憶體分配,此處以hotspot vm為例(官方jdk採用的vm) 程式計數器 棧 1. 虛擬機棧 2. 本地方法棧 Java堆 堆記憶體是各個線程共用的區域 方法區 它用於存儲已經被虛擬機載入的類信息、常量、靜態變數、即編譯器編譯後的代碼等數據。靜態變數、常量在方法區 ...
  • 根據不同的條件,調用不同的 bean 對象,執行對象中的方法 SpringUtils 工具類 package com.vipsoft.web.utils; import cn.hutool.core.util.ArrayUtil; import org.springframework.aop.fra ...
一周排行
    -Advertisement-
    Play Games
  • 前言 本文介紹一款使用 C# 與 WPF 開發的音頻播放器,其界面簡潔大方,操作體驗流暢。該播放器支持多種音頻格式(如 MP4、WMA、OGG、FLAC 等),並具備標記、實時歌詞顯示等功能。 另外,還支持換膚及多語言(中英文)切換。核心音頻處理採用 FFmpeg 組件,獲得了廣泛認可,目前 Git ...
  • OAuth2.0授權驗證-gitee授權碼模式 本文主要介紹如何筆者自己是如何使用gitee提供的OAuth2.0協議完成授權驗證並登錄到自己的系統,完整模式如圖 1、創建應用 打開gitee個人中心->第三方應用->創建應用 創建應用後在我的應用界面,查看已創建應用的Client ID和Clien ...
  • 解決了這個問題:《winForm下,fastReport.net 從.net framework 升級到.net5遇到的錯誤“Operation is not supported on this platform.”》 本文內容轉載自:https://www.fcnsoft.com/Home/Sho ...
  • 國內文章 WPF 從裸 Win 32 的 WM_Pointer 消息獲取觸摸點繪製筆跡 https://www.cnblogs.com/lindexi/p/18390983 本文將告訴大家如何在 WPF 裡面,接收裸 Win 32 的 WM_Pointer 消息,從消息裡面獲取觸摸點信息,使用觸摸點 ...
  • 前言 給大家推薦一個專為新零售快消行業打造了一套高效的進銷存管理系統。 系統不僅具備強大的庫存管理功能,還集成了高性能的輕量級 POS 解決方案,確保頁面載入速度極快,提供良好的用戶體驗。 項目介紹 Dorisoy.POS 是一款基於 .NET 7 和 Angular 4 開發的新零售快消進銷存管理 ...
  • ABP CLI常用的代碼分享 一、確保環境配置正確 安裝.NET CLI: ABP CLI是基於.NET Core或.NET 5/6/7等更高版本構建的,因此首先需要在你的開發環境中安裝.NET CLI。這可以通過訪問Microsoft官網下載並安裝相應版本的.NET SDK來實現。 安裝ABP ...
  • 問題 問題是這樣的:第三方的webapi,需要先調用登陸介面獲取Cookie,訪問其它介面時攜帶Cookie信息。 但使用HttpClient類調用登陸介面,返回的Headers中沒有找到Cookie信息。 分析 首先,使用Postman測試該登陸介面,正常返回Cookie信息,說明是HttpCli ...
  • 國內文章 關於.NET在中國為什麼工資低的分析 https://www.cnblogs.com/thinkingmore/p/18406244 .NET在中國開發者的薪資偏低,主要因市場需求、技術棧選擇和企業文化等因素所致。歷史上,.NET曾因微軟的閉源策略發展受限,儘管後來推出了跨平臺的.NET ...
  • 在WPF開發應用中,動畫不僅可以引起用戶的註意與興趣,而且還使軟體更加便於使用。前面幾篇文章講解了畫筆(Brush),形狀(Shape),幾何圖形(Geometry),變換(Transform)等相關內容,今天繼續講解動畫相關內容和知識點,僅供學習分享使用,如有不足之處,還請指正。 ...
  • 什麼是委托? 委托可以說是把一個方法代入另一個方法執行,相當於指向函數的指針;事件就相當於保存委托的數組; 1.實例化委托的方式: 方式1:通過new創建實例: public delegate void ShowDelegate(); 或者 public delegate string ShowDe ...