.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;
        }
    }
}
相关推荐
wangl_921 天前
C# / .NET 在工业环境中的优势
开发语言·c#·.net·.netcore·.net core·visual studio
△曉風殘月〆1 天前
如何在WPF中使用 Fluent 主题
wpf
△曉風殘月〆1 天前
不同.NET版本中的WPF新增功能
.net·wpf
海盗12341 天前
WPF使用内置资源系统实现国际化
wpf
Rotion_深1 天前
WPF UserControl 和 CustomControl
wpf
SEO-狼术1 天前
Run Secure SFTP Across Every Platform
pdf·wpf
c#上位机2 天前
wpf之RadialGradientBrush径向渐变画刷
wpf
不懂的浪漫2 天前
OpenTelemetry 和 SkyWalking Agent 怎么选?一次讲清 OTel、SkyWalking Agent 的相同点与区别
wpf·skywalking·链路追踪·opentelemetry·otel
c#上位机2 天前
wpf之LinearGradientBrush线性渐变
wpf