如何在 Prism 中将服务注册为瞬态服务

How to register service as transient in Prism

最近我在WPF项目中使用了Prism.DryIoC库。我在 App.xaml.cs class 中发现要覆盖 RegisterTypes 方法

using Prism.Ioc;
using WpfAppNetCore.Views;
using System.Windows;

namespace WpfAppNetCore
{
    public partial class App
    {
        protected override Window CreateShell()
        {
            return Container.Resolve<MainWindow>();
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            // Register as Singleton 
            containerRegistry.RegisterSingleton<ITest, Test>();
        }
    }
}

我有一个 class 的实现,它继承自 ITest 接口,如下所示:

ITest.cs

namespace WpfAppNetCore
{
    public interface ITest
    {
        string GetTime { get; set; }
    }
}

Test.cs

using System;

namespace WpfAppNetCore
{
    public class Test : ITest
    {
        #region Implementation of ITest

        public string GetTime { get; set; } = $"{DateTime.Now:dd/MM/yyyy HH:mm:ss.ffff}";

        #endregion
    }
}

在 ViewModel 中,我在 ITest 中调用了 GetTime 属性,并通过了 for 循环。

public MainWindowViewModel(ITest test)
        {
            var sb = new StringBuilder();

            for (var i = 0; i < 10; i++)
            {
                sb.AppendLine(test.GetTime);
                Thread.Sleep(100);
            }

            Message = sb.ToString();
        }

如果我将 ITest 注册为 Singleton 服务,我将得到相同的结果,这符合我的意图。

但我不知道如何将 ITest 注册为 Transient Scope 服务,以便在每次迭代后得到不同的结果。

有关如何注册服务的更多信息,您可能需要查看 Prism and also the docs for the Prism.Container.Extensions 的文档,其中提供了许多更强大的选项。除非别无选择,否则永远不要调用 GetContainer()。使用 Container Extensions 包,您永远不会有这种需要。

这似乎是 XY problem

 public string GetTime { get; set; } = $"{DateTime.Now:dd/MM/yyyy HH:mm:ss.ffff}";

上面只会在父对象初始化的时候设置那个属性的初始值

在这个例子中

public MainWindowViewModel(ITest test) {
    var sb = new StringBuilder();

    for (var i = 0; i < 10; i++) {
        sb.AppendLine(test.GetTime);
        Thread.Sleep(100);
    }

    Message = sb.ToString();
}

无论注入的依赖是单例还是瞬态,循环中都会返回相同的初始值。

根据源代码存储库,只需调用 Register

protected override void RegisterTypes(IContainerRegistry containerRegistry) {
    // Register as Transient
    containerRegistry.Register<ITest, Test>();
}

会将映射类型注册为瞬态。