问题描述
设置此设置:
Page1:
- Component A
- Component B
Page2:
- Component C
- Component D
Service: MyService
我希望组件A和B获得相同的MyService实例.
I want Component A und B to get the same instance of MyService.
组件C和D应该获得MyService的新的(和相同的)实例.
Component C and D should get a fresh (and the same) instance of MyService.
当我将MyService注册为 transient
时,每个组件都会获得一个新的实例.
When I register MyService as transient
each Component gets a fresh instance.
当我注册为 singleton
/ scoped
时,所有组件都共享同一实例.
When I register as singleton
/scoped
all components share the same instance.
组件是库的一部分,因此我正在寻找不需要消耗方或只需花费很少精力的解决方案.
Components are part of library and thus I am looking for solution that requries no or very little effort on the consuming side.
怎么办?
推荐答案
好像没有内置的方法可以处理它.因此,我选择了单例工厂,并将其链接到NavigationManager.
Looks like there is no built-in way to handle it. So I went with the singleton factory and linked it to the NavigationManager.
public class MyServiceFactory
{
private NavigationManager _navigationManager;
private Dictionary<string, MyService> _state = new Dictionary<string, MyService>();
public MyServiceFactory(NavigationManager navigationManager)
{
_navigationManager = navigationManager;
_navigationManager.LocationChanged += (s, e) =>{
_state.Remove(_state.Keys.Single(x => x != e.Location));
};
}
public MyService Get()
{
if(!_state.ContainsKey(_navigationManager.Uri))
{
_state.Add(_navigationManager.Uri, new MyService());
}
return _state[_navigationManager.Uri];
}
}
}
这篇关于Blazor和Navigation的服务生命周期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!