WPF 中的 AddScoped 和 AddSingleton 有什么区别吗?

问题描述 投票:0回答:1

在 WPF 或任何不作为服务 Web 请求的 Web 应用程序运行的控制台应用程序的上下文中,如果我使用

Microsoft.Extensions.DependencyInjection
AddScopedAddSingleton 方法有何不同?

读完这个问题后我开始思考:

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);
        ServiceCollection services = new ServiceCollection();
        services.AddSingleton<MainViewModel>(); //how is this
        //services.AddSingleton<MainViewModel>(); //different than this

        services.AddSingleton<MainWindow>();
        services.AddScoped<MainWindow>();

        var serviceProvider = services.BuildServiceProvider();
        MainWindow = serviceProvider.GetService<MainWindow>();
        MainWindow.Show();
    }
}
c# wpf dependency-injection
1个回答
0
投票

有区别!举例来说,您在 WPF 中有一个自定义导航(您应该这样做),在视图(用户控件)和 VM(视图模型类)上使用 AddSingleton。这样,每当用户在视图之间导航时,视图和虚拟机数据都会保存在内存中,不需要重新加载/重新创建。如果您使用 AddScoped,实例将在某个时刻被清理,并且在导航中可能会重新创建它们(取决于 GC)。

当然,如果我们以 MainWindow 为例,您需要重新创建的概率接近于零,在这种特殊情况下,我会说没有差异

© www.soinside.com 2019 - 2024. All rights reserved.