最近,我已将Prism.DryIoC库用于WPF项目。我在App.xaml.cs类中发现要重写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>();
}
}
}
我有一个从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注册为瞬态范围服务,以便在每次迭代后获得不同的结果。
Container.RegisterType<IInetrface, Implementation>(new TransientLifetimeManager());
对于棱镜7.2:
containerRegistry.GetContainer().RegisterType(typeof(IInterface), typeof(Implementation), nameof(IInterface), new TransientLifetimeManager());
[扩展方法允许在Microsoft.Practices.Unity名称空间中使用通用的ResiterType / Resolve方法,该方法可以与NuGet一起安装,但似乎它们已在较新版本中删除了这些方法。