Service Lifetimes in Blazor and Navigation

非 Y 不嫁゛ 提交于 2021-01-29 12:05:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!