首页 > 解决方案 > 使用 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);
    }
}

这是正确的方法吗?

标签: c#.netsimple-injector

解决方案


您只需将它们都注册为单例:

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);
}

推荐阅读