Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
228 views
in Technique[技术] by (71.8m points)

WPF .Net Core 3.1 AddSingleton 作用域无效

### 问题描述
在App.xaml.cs中注入了Config类的单个实例, 在MainWindow中对修改了config的属性, 但是在Blaster中config是一个新的实例.
TryAddSingleton的生命周期和作用域完全无效, 请高手帮忙解答下. 非常感谢!

App.xaml.cs

public partial class App
{
    protected override void OnStartup(StartupEventArgs e)
    {
        Init();
        base.OnStartup(e);
    }
    
    private void ConfigureServices(IServiceCollection services)
    {
        //日志
        services.TryAddSingleton<Log>();
        //配置
        services.TryAddSingleton<Config>();
        //机器人
        services.TryAddSingleton<Blaster>();
        //主界面
        services.TryAddTransient<MainWindow>();
    }

    private void Init()
    {
        IServiceCollection services = new ServiceCollection();
        ConfigureServices(services);
        services.BuildServiceProvider()
            .GetRequiredService<MainWindow>()
            .Show();
    }
}

MainWindow.xmal.cs 中修改了config

    public MainWindow(Log logger, Config config, Blaster blaster)
    {
        InitializeComponent();
        _logger = logger;
        _config = config;
        _blaster = blaster;
        _path = $"{System.Environment.CurrentDirectory}\config.tmp";
        ReadConfig();
        Main.DataContext = _config;
    }

    /// <summary>
    /// 读取数据
    /// </summary>
    private void ReadConfig()
    {
        if (!File.Exists(_path)) return;
        var content = File.ReadAllText(_path);
        if (content.TryJsonParse(out Config config, out _))
        {
            _config = config;
        }
    }
Blaster.cs中的config是一个新的实例, 内存地址和MainWindow中的config不同
    public Blaster(Log logger, Config config)
    {
        _logger = logger;
        _config = config;
        _path = Environment.CurrentDirectory + "\cache.tmp";
        ReadData();
    }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神解答

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...