c# - 使用 Simple Injector,是否可以通过其实现类型获得单例?
问题描述
如果我在容器中注册,例如:
container.Register<IShell, ShellViewModel>(Lifestyle.Singleton);
有没有办法使用“实现类型”获得相同的实例ShellViewModel
?
例子:
container.GetInstance<ShellViewModel>();
上面的行返回一个不同于container.GetInstance<IShell>()
. 如何确保两个调用的实例相同?
我使用ResolveUnregisteredType
事件解决它。
private void ContainerResolveUnregisteredType(
object sender, UnregisteredTypeEventArgs e)
{
var producer = container.GetRootRegistrations()
.FirstOrDefault(r => r.Registration
.ImplementationType == e.UnregisteredServiceType);
if (producer != null && producer.Lifestyle == Lifestyle.Singleton)
{
var registration = producer.Lifestyle
.CreateRegistration(
e.UnregisteredServiceType,
producer.GetInstance,
container);
e.Register(registration);
}
}
这是正确的方法吗?
解决方案
您只需将它们都注册为单例:
container.RegisterSingleton<ShellViewModel>();
container.RegisterSingleton<IShell, ShellViewModel>();
UDPATE
确认使用简单的单元测试:
[TestMethod]
public void RegisterSingleton_TwoRegistrationsForTheSameImplementation_ReturnsTheSameInstance()
{
var container = new Container();
container.RegisterSingleton<ShellViewModel>();
container.RegisterSingleton<IShell, ShellViewModel>();
var shell1 = container.GetInstance<IShell>();
var shell2 = container.GetInstance<Shell>();
Assert.AreSame(shell1, shell2);
}
推荐阅读
- .net - 如何检测用户是否正在与 PowerPoint 中的“文件选项卡”进行交互?
- jquery - 完整的日历 ajax 事件插入未在日历上呈现
- python - 从 CircularBlockBootstrap 到 Blockbootstrap
- java - 在java中将俱乐部分类为联赛的最佳方法是什么
- geolocation - 大型数据集的反向地理编码(>= 500,000 行)
- arrays - 使用jq如何查询和替换数组中的值
- python - 高效的 Numpy 数组乘法和整形
- pandas - 减少数据框->获取列中每个级别的最后一行
- sql - INSERT 中的某种 IF 条件
- javascript - 如何在我的函数中实现标准输入和标准输出