Skip to content

Instantly share code, notes, and snippets.

@dylanberry
Created May 16, 2019 16:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dylanberry/4a24df4fb369770e43b8a3e34997f854 to your computer and use it in GitHub Desktop.
Save dylanberry/4a24df4fb369770e43b8a3e34997f854 to your computer and use it in GitHub Desktop.
using HttpTracer;
using System.Net.Http;
using Microsoft.AspNetCore.Components.Browser;
using Microsoft.AspNetCore.Components.Builder;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Components;
using System;
using Microsoft.AspNetCore.Blazor.Services;
using Microsoft.AspNetCore.Blazor.Http;
using System.Threading.Tasks;
namespace WebApplication1
{
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<IMyService, MyService>();
services.AddTransient<MyHandler>();
services.AddSingleton<HttpClient>(s =>
{
// Creating the URI helper needs to wait until the JS Runtime is initialized, so defer it.
var uriHelper = s.GetRequiredService<IUriHelper>();
var myHandler = s.GetRequiredService<MyHandler>();
myHandler.InnerHandler = new WebAssemblyHttpMessageHandler();
return new HttpClient(myHandler)
{
BaseAddress = new Uri(WebAssemblyUriHelper.Instance.GetBaseUri())
};
});
}
public void Configure(IComponentsApplicationBuilder app)
{
app.AddComponent<App>("app");
}
}
// I know, I'm a monster.
public class MyHandler : DelegatingHandler
{
private readonly IMyService _myService;
public MyHandler(IMyService myService)
{
_myService = myService;
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken)
{
_myService.MyMethod();
return base.SendAsync(request, cancellationToken);
}
}
public interface IMyService
{
void MyMethod();
}
public class MyService : IMyService
{
public void MyMethod() => Console.WriteLine("Hello from MyService.MyMethod");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment