简体   繁体   中英

Blazor service injection not working properly

I have this code in Blazor 3.0.0-preview4-19216-03 targeting a client app:

namespace BlazorShared.Services
{
    public interface ILogin
    {
        Task<string> Login();
    }

    public class LoginService : ILogin
    {
        private HttpClient _client;

        public LoginService(HttpClient client)
        {
            _client = client;
        }

        public async Task<string> Login()
        {
            var myclient = new HttpClient();

            var responseMessage = await myclient.GetAsync("http://www.google.es");
            var content = await responseMessage.Content.ReadAsStringAsync();

            Debug.WriteLine(content);

            return content;
        }
    }
}

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddSingleton<ILogin, LoginService>();
    }

    public void Configure(IComponentsApplicationBuilder app)
    {
        app.AddComponent<App>("app");
    }
}

and this HTML

@functions {
    public async Task Submit()
    {
        var str = await LoginService.Login(null, null, null);
        Console.WriteLine(str);
    }
}

Full Razor file: https://pastebin.com/3LbQQvk0

I have tested it and the web request never gets done and I'm not able to show the service response in the client. I have tried debugging in chrome following the instructions And I see the service method is being called but the constructor of the service is not, and as I understood Blazor should inject the HttpClient. Any ideas what can be happening? Thanks.

The following is wrong even if it is not the culprit... In the LoginService you define an HttpClient variable into which you assign an instance of HttpClient provided by DI. On the other hand, you define a new HttpClient object named myclient and use it in the Login method.

You should use the object provided by DI. You shouldn't yourself define HttpClient objects. Why ? Because Blazor configure for you the HttpClient it creates. For instance, setting the Document base URI, which enable your web app to be navigated as an SPA app.

Hope this helps...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM