You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET MAUI中如何通过依赖注入使用IConfiguration读取appsettings.json

解决方案:在非标准MAUI Windows项目中集成IConfiguration与依赖注入

核心问题分析

你当前手动实现的ServiceContainer脱离了MAUI自带的依赖注入体系,导致无法注册和注入IConfiguration。需要改用MAUI官方的DI配置方式,同时正确加载appsettings.json。


步骤1:调整appsettings.json属性

确保文件的生成操作设置为「嵌入的资源」(右键文件→属性→生成操作),保持「复制到输出目录」为「不复制」(和你原来的设置一致)。


步骤2:重构MauiProgram.cs,集成IConfiguration与DI

删除你自定义的ServiceContainer,改用MAUI自带的MauiAppBuilder来配置DI和读取配置:

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;

namespace Ubisoft.Coffee;

public static class MauiProgram
{
    public static MauiApp CreateMauiApp()
    {
        var builder = MauiApp.CreateBuilder();

        // 1. 加载嵌入的appsettings.json到IConfiguration
        var assembly = typeof(MauiProgram).Assembly;
        // 注意:资源名称格式为「项目命名空间.文件名」,请根据实际情况修改
        var configStream = assembly.GetManifestResourceStream("Ubisoft.Coffee.appsettings.json");
        if (configStream != null)
        {
            builder.Configuration.AddJsonStream(configStream);
        }

        // 2. 注册服务与ViewModel
        builder.Services.AddScoped<IFileServices, FileServices>();
        builder.Services.AddScoped<DashboardViewModel>();
        builder.Services.AddScoped<SettingsViewModel>();

        // 3. 注册页面(MAUI会自动通过DI注入ViewModel)
        builder.Services.AddTransient<SettingsPage>();
        builder.Services.AddTransient<DashboardPage>();

        // 初始化MAUI应用
        builder
            .UseMauiApp<App>()
            .ConfigureFonts(fonts =>
            {
                fonts.AddFont("OpenSans-Regular.ttf", "OpenSansRegular");
            });

        return builder.Build();
    }
}

步骤3:在ViewModel中注入IConfiguration(或强类型配置)

方式1:直接注入IConfiguration

在ViewModel的构造函数中接收IConfiguration,即可读取配置项:

using Microsoft.Extensions.Configuration;

namespace Ubisoft.Coffee.ViewModels;

public class DashboardViewModel
{
    private readonly IConfiguration _config;
    private readonly IFileServices _fileServices;

    public DashboardViewModel(IConfiguration config, IFileServices fileServices)
    {
        _config = config;
        _fileServices = fileServices;

        // 示例:读取数据库连接字符串
        var dbConnStr = _config.GetConnectionString("DefaultConnection");
    }
}

方式2:使用强类型配置(推荐)

创建对应配置结构的实体类:

namespace Ubisoft.Coffee.Models;

public class AppSettings
{
    public string DefaultConnection { get; set; } = string.Empty;
    // 可添加其他配置项,如AppTitle、MaxFileSize等
}

在MauiProgram中绑定配置:

// 新增:绑定强类型配置
builder.Services.Configure<AppSettings>(builder.Configuration);

然后在ViewModel中注入IOptions<AppSettings>:

using Microsoft.Extensions.Options;

namespace Ubisoft.Coffee.ViewModels;

public class DashboardViewModel
{
    private readonly AppSettings _settings;
    private readonly IFileServices _fileServices;

    public DashboardViewModel(IOptions<AppSettings> settings, IFileServices fileServices)
    {
        _settings = settings.Value;
        _fileServices = fileServices;

        // 读取配置项
        var dbConnStr = _settings.DefaultConnection;
    }
}

步骤4:调整页面的BindingContext

删除App.xaml中注册的SeriviceContainer静态资源,改用DI自动注入ViewModel:

在页面的代码后台,通过构造函数接收ViewModel并设置为BindingContext:

namespace Ubisoft.Coffee.Pages;

public partial class SettingsPage : ContentPage
{
    public SettingsPage(SettingsViewModel viewModel)
    {
        InitializeComponent();
        BindingContext = viewModel;
    }
}

此时XAML中无需手动设置BindingContext,代码如下:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:toolkit="http://schemas.microsoft.com/dotnet/2022/maui/toolkit"  
             x:Class="Ubisoft.Coffee.Pages.SettingsPage"
             Title="SettingsPage">
    <!-- 页面内容 -->
</ContentPage>

注意事项

  • 确认嵌入资源名称正确:可以在调试时通过assembly.GetManifestResourceNames()查看所有嵌入资源的完整名称,避免拼写错误。
  • 强类型配置需要保证appsettings.json的结构与实体类属性完全匹配(大小写敏感)。
  • MAUI的DI默认支持构造函数注入,无需手动实例化ViewModel或服务。

内容的提问来源于stack exchange,提问作者iChuan love iKun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.18 05:05:01