注销 view-Viewmodel Prism xamarin dryioc
Unregister view-Viewmodel Prism xamarin dryioc
我有一种情况需要取消注册 ViewModel 并重新注册它。
原因是有时我想注入 "fakeservice" 而不是 "real one"。
因此,如果我按下 "offline" 按钮,我需要取消注册 viewModels 并重新注册它们,以便使用 Fakeservices。
如何使用 prism 和 dryioc 注销视图视图模型
我通常这样注册:
protected override void RegisterTypes(Prism.Ioc.IContainerRegistry containerRegistry)
{
containerRegistry.RegisterForNavigation<MyPage,MyPageViewModel>();
}
如何注销以上内容?
谢谢
The reason is that at times I want to inject a "fakeservice" rather than the "real one".
无需注销视图模型。创建实例时注入服务。
但是您无论如何都不应该为此使用容器 - 创建一个服务提供者,然后您可以将该服务提供者切换到当前活动的服务。如果服务提供者自己实现服务接口,这对消费者来说甚至是透明的。
public interface IService
{
void DoStuff();
}
public interface IServiceProvider
{
void SetActiveService( Type serviceType );
}
internal ServiceProvider : IServiceProvider, IService
{
void IService.DoStuff() => _currentService.DoStuff();
public void SetActiveService( Type serviceType )
{
_currentService = _container.Resolve( serviceType );
}
private IService _currentService;
}
不过,添加一些同步和错误处理并重构生产环境中的容器引用。
使用 Unity,我会将提供程序注册为未命名的标准实现,并将所有实际服务注册为命名实现,并将 IEnumerable<Func<IService>>
注入到服务提供程序中。也许 DryIoc 提供了类似的功能。
当您使用该扩展注册 View 和 ViewModel 时,值得注意的是 ViewModel 本身并未向容器注册,它仅向 ViewModelLocationProvider 注册,后者提供 ViewModel 类型以解析给定的 View。
这里还值得注意的是,ViewModel 是通过瞬态生命周期解析的,这意味着每次解析时都会得到一个新实例,因此您真正需要做的就是导航离开然后再返回。
我有一种情况需要取消注册 ViewModel 并重新注册它。
原因是有时我想注入 "fakeservice" 而不是 "real one"。
因此,如果我按下 "offline" 按钮,我需要取消注册 viewModels 并重新注册它们,以便使用 Fakeservices。
如何使用 prism 和 dryioc 注销视图视图模型
我通常这样注册:
protected override void RegisterTypes(Prism.Ioc.IContainerRegistry containerRegistry)
{
containerRegistry.RegisterForNavigation<MyPage,MyPageViewModel>();
}
如何注销以上内容?
谢谢
The reason is that at times I want to inject a "fakeservice" rather than the "real one".
无需注销视图模型。创建实例时注入服务。
但是您无论如何都不应该为此使用容器 - 创建一个服务提供者,然后您可以将该服务提供者切换到当前活动的服务。如果服务提供者自己实现服务接口,这对消费者来说甚至是透明的。
public interface IService
{
void DoStuff();
}
public interface IServiceProvider
{
void SetActiveService( Type serviceType );
}
internal ServiceProvider : IServiceProvider, IService
{
void IService.DoStuff() => _currentService.DoStuff();
public void SetActiveService( Type serviceType )
{
_currentService = _container.Resolve( serviceType );
}
private IService _currentService;
}
不过,添加一些同步和错误处理并重构生产环境中的容器引用。
使用 Unity,我会将提供程序注册为未命名的标准实现,并将所有实际服务注册为命名实现,并将 IEnumerable<Func<IService>>
注入到服务提供程序中。也许 DryIoc 提供了类似的功能。
当您使用该扩展注册 View 和 ViewModel 时,值得注意的是 ViewModel 本身并未向容器注册,它仅向 ViewModelLocationProvider 注册,后者提供 ViewModel 类型以解析给定的 View。
这里还值得注意的是,ViewModel 是通过瞬态生命周期解析的,这意味着每次解析时都会得到一个新实例,因此您真正需要做的就是导航离开然后再返回。