如果我在容器中注册如下:
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);
}
关于c# - 使用简单注入(inject)器,是否可以通过其实现类型获取单例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57292138/