问题
Asumme this setup:
Page1:
- Component A
- Component B
Page2:
- Component C
- Component D
Service: MyService
I want Component A und B to get the same instance of MyService.
Component C and D should get a fresh (and the same) instance of MyService.
When I register MyService as transient
each Component gets a fresh instance.
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.
How can it be done?
回答1:
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];
}
}
}
来源:https://stackoverflow.com/questions/58363327/service-lifetimes-in-blazor-and-navigation