.net core8 WPF 依赖注入(DI)

创建两个窗口,MainWindow、Window1

App.xaml中删除: StartupUri="MainWindow.xaml",不需要系统自动创建,用手动创建,不删除会变报

System.Windows.Markup.XamlParseException:""在类型"WpfApp1.MainWindow"上未找到匹配的构造函数。可以使用 Arguments 或 FactoryMethod 指令来构造此类型。

错误,因为这个是自动创建窗口并且需要调用窗口无参构造函数。

代码:

cs 复制代码
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Configuration;
using System.Data;
using System.Windows;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public static IServiceProvider ServiceProvider { get; private set; } 

        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);

            var services = new ServiceCollection();
            ConfigureServices(services);

            // 构建容器 + 创建Scope
            ServiceProvider = services.BuildServiceProvider(); 

            // 启动主窗口
            var mainWindow = ServiceProvider.GetRequiredService<MainWindow>();
            mainWindow.Show();
        }

        private void ConfigureServices(ServiceCollection services)
        {
            // 1. 标准配置构建(官方推荐)
            IConfiguration configuration = new ConfigurationBuilder()
                .SetBasePath(AppContext.BaseDirectory) // 标准路径
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .Build();

            // 2. 注入配置到DI(全局可用)
            services.AddSingleton(configuration);

            // 3. 安全获取连接字符串
            var connectionString = configuration.GetSection("ConnectionStrings");
            if (connectionString == null)
            {
                MessageBox.Show("请配置数据库连接字符串");
                Current.Shutdown();
                return;
            }

            // 4. 注册数据库上下文
            services.AddDbContext<AppDbContext>(options =>
                options.UseSqlServer(connectionString.Value));

            // 5. 注册业务服务
            services.AddScoped<Ibase_Sense, base_SenseService>();

            // 6. 窗口注册 Transient(推荐!不要用Singleton)
            services.AddTransient<MainWindow>();
            services.AddTransient<Window1>();
        }

        // 应用退出 释放资源
        protected override void OnExit(ExitEventArgs e)
        { 
            if (ServiceProvider != null)
            {
                (ServiceProvider as IDisposable)?.Dispose();
            }
            base.OnExit(e);
        }
    }

}
cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfApp1
{
    public interface Ibase_Sense
    {
        string getDateTime();
    }
}
cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WpfApp1
{
    public class base_SenseService : Ibase_Sense
    {
        string Ibase_Sense.getDateTime()
        {
            return System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        }
    }
}
cs 复制代码
using Microsoft.Extensions.DependencyInjection;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private Ibase_Sense ibase_Sense { get; set; }
        public MainWindow(Ibase_Sense _Sense)
        {
            InitializeComponent();
            this.ibase_Sense = _Sense;    
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            string x = ibase_Sense.getDateTime();
        }
        protected void BtnClick(object sender, RoutedEventArgs e)
        {
            var window = App.ServiceProvider.GetRequiredService<Window1>();
            window.Show();
        }
    }
}
cs 复制代码
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WpfApp1
{
    /// <summary>
    /// Window1.xaml 的交互逻辑
    /// </summary>
    public partial class Window1 : Window
    {
        private Ibase_Sense ibase_Sense { get; set; }
        public Window1(Ibase_Sense _Ibase_Sense)
        {
            InitializeComponent();
            this.ibase_Sense = _Ibase_Sense;
        }
    }
}
相关推荐
陈仓主教1 小时前
# WPF CheckBox 控件详解与使用—WPF 中的控件(6)--复选框控件(CheckBox)
wpf
1-1=01 天前
C# IO和序列化
c#·.net·.netcore
宝桥南山2 天前
.NET 11 - 尝试一下Blazor中的新特性SupplyParameterFromTempData
microsoft·微软·c#·asp.net·.net·.netcore
光泽雨2 天前
WPF 音视频四大核心方案对比
wpf·音视频
浪扼飞舟3 天前
WPF(数据绑定)
wpf
1-1=03 天前
C# 特性(Attribute)
c#·.net·.netcore
samble4 天前
从零搭建半导体设备上位机(四):单实例、启动流程与配置文件,App 里那 526 行到底在干什么
wpf·配置文件·单实例
淡海水4 天前
10-01-互操作-C#与C++边界的内存管理
unity·c#·游戏引擎·.netcore·gc
1-1=04 天前
C# 反射
c#·.net·.netcore
浪扼飞舟4 天前
WPF(控件的继承树、内容控件、布局控件)
wpf