使用简单注入器,是否可以通过其实现类型获得单例?
Using the Simple Injector, is it possible to get a singleton by its implementation type?
如果我在容器中注册如下:
container.Register<IShell, ShellViewModel>(Lifestyle.Singleton);
有没有办法使用“实现类型”获得相同的实例ShellViewModel
?
示例:
container.GetInstance<ShellViewModel>();
上面的行returns是一个不同于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);
}
如果我在容器中注册如下:
container.Register<IShell, ShellViewModel>(Lifestyle.Singleton);
有没有办法使用“实现类型”获得相同的实例ShellViewModel
?
示例:
container.GetInstance<ShellViewModel>();
上面的行returns是一个不同于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);
}