WPF使用依赖注入

现在依赖注入在.Net里面已经普及,自己常写一些简单的demo倒是无所谓,但偶尔写一点正式的工程,也免不了要使用一下,于是总结了一下在WPF里面使用依赖注入。

在写简单Demo时候,通常是在MainWindow的构造函数里面直接做初始化,各种变量也都丢在MainWindow类里面。在使用依赖注入后,我发现在App里面完成一些初始化内容更合适,包括MainWindow也通过容器生成,需要注意的是,记得把App.xaml中的 StartupUri更改为 Startup,并把值改为自定义的启动函数,在启动函数里面调用MainWindow的Show方法。

App.xaml.cs

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog;
using NLog.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Net.WebSockets;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
using System.Windows;

namespace TradeClient
{
    /// 
    /// Interaction logic for App.xaml
    /// 
    public partial class App : Application
    {
        public App()
        {
            LogManager.Configuration.Variables["ProgramName"] = System.Reflection.Assembly.GetExecutingAssembly().GetName().Name;
            LogManager.Configuration.Variables["StartTime"] = DateTime.Now.ToString("yyyyMMdd-HHmmss");

            var config = new ConfigurationBuilder().Build();
            var servicesCollection = new ServiceCollection();
            servicesCollection.AddLogging(loggingBuilder => loggingBuilder.AddNLog(config));
            servicesCollection.AddSingleton();
            servicesCollection.AddSingleton();
            servicesCollection.AddSingleton();
            servicesCollection.AddSingleton();
            ServiceProvider = servicesCollection.BuildServiceProvider();

            TradeSpiMiddle tradeSpiMiddle = ServiceProvider.GetRequiredService();
            tradeSpiMiddle.InitTradeSpi(ref TradeSpi);
            int size = Marshal.SizeOf(TradeSpi);
            TradeSpiPoint = Marshal.AllocHGlobal(size);
            Marshal.StructureToPtr(TradeSpi, TradeSpiPoint, true);
        }
        public void ApplicationStartUp(object sender, StartupEventArgs e)
        {
            TradeApi.CreateTradeApi();
            TradeApi.RegisterSpi(TradeSpiPoint);
            TradeApi.RegisterFront("127.0.0.1", 10001);
            TradeApi.Init();

            MainWindow mainWindow = ServiceProvider.GetRequiredService();
            mainWindow.Show();
        }



        private TradeSpi TradeSpi = new();
        private IntPtr TradeSpiPoint;
        private ServiceProvider ServiceProvider;
    }
}

你可能感兴趣的:(紫云的程序人生,C#,wpf)