.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;
        }
    }
}
相关推荐
csdn_aspnet16 小时前
C# .NetCore Swagger ISchemaFilter 处理枚举、特殊类型
c#·.netcore·swagger
code_long21 小时前
.net core 连接打印机 使用zpl指令打印机,并且位图本地渲染zpl指令
c#·.netcore·位图·打印机·模板编辑·模板预览
csdn_aspnet1 天前
C# .NetCore Swagger ISchemaFilter Long 转 String 防精度丢失
c#·.netcore·swagger
donk13142 天前
React Native for OpenHarmony 实战:三方库 react-native-circular-action-menu 的鸿蒙化适配指南
javascript·分布式·react native·react.js·wpf·harmonyos
csdn_aspnet2 天前
C# .NetCore Swagger ISchemaFilter 注入示例值、描述
c#·.netcore·swagger
donk13143 天前
React Native for OpenHarmony 实战:三方库 react-native-step-indicator 的鸿蒙化适配指南
分布式·react native·react.js·wpf·harmonyos
He BianGu3 天前
【笔记】WPF中RenderOptions类的详细功能
笔记·wpf
VidDown3 天前
上线三个月后的第一次事故:一个 Django 服务的日志、监控与故障复盘
数据库·python·django·wpf·音视频·视频编解码
He BianGu3 天前
【笔记】WPF中CachingHint的功能
笔记·wpf
He BianGu3 天前
【笔记】在WPF中BitmapScalingMode的作用
笔记·wpf