Suchiman / BlazorDualMode

Demo on how to run dynamically in client or server side mode
MIT License
145 stars 24 forks source link

Injected Services get error when Refresh a page that has one #13

Closed ghost closed 4 years ago

ghost commented 4 years ago

In the client I have a Singletone service (named GenericService) that uses System.Net.HttpClient (injected in its constructor), When I refresh the page or type ?mode=server to debug, Blazor gets this error: InvalidOperationException: Cannot consume scoped service 'System.Net.Http.HttpClient' from singleton 'Job.Client.ServiceInterfaces.IGenericService'. I copied all of my service registrations from Client startup to the server startup.


services.AddMvc();            
            services.AddServerSideBlazor();
            services.AddResponseCompression(opts =>
            {
                opts.MimeTypes = ResponseCompressionDefaults.MimeTypes.Concat(
                    new[] { "application/octet-stream" });
            });  
            services.AddSingleton<ITokenService, TokenService>();
            services.AddSingleton<IGenericService, GenericService>();
            services.AddSingleton<II18nService, RemoteI18nService>();
            services.AddSingleton<ViewDataService>();
            services.AddHttpContextAccessor();
            services.AddSingleton<HttpContextAccessor>();
            // Server Side Blazor doesn't register HttpClient by default
            if (!services.Any(x => x.ServiceType == typeof(HttpClient)))
            {
                // Setup HttpClient for server side in a client side compatible fashion
                services.AddScoped<HttpClient>(s =>
                {
                    // Creating the URI helper needs to wait until the JS Runtime is initialized, so defer it.
                    var uriHelper = s.GetRequiredService<NavigationManager>();
                    return new HttpClient
                    {
                        BaseAddress = new Uri(uriHelper.BaseUri)
                    };
                });
            }
  How this be corrected?    
ghost commented 4 years ago

Sorry for the repeated question, Registering GenericService with AddScoped() solved the problem.