I’m facing a problem that my proxy is being invoked when one of my MagicOnion methods are called. When I learned how to use DispatchProxy, it was straightforward to use but turning onto the environment with .NET Core and MagicOnion, the situation gets much more complicated.
My Program.cs
has this configuration lines:
builder.Services.AddScoped(provider => MyProxy<IRTCHub>.Create(new RTCHub(provider, provider.GetRequiredService<ILogger<RTCHub>>())));
builder.Services.AddDbContext<VehicleContext>();
builder.Services.AddSingleton<UserManager>();
builder.Services.AddGrpc();
builder.Services.AddMagicOnion();
var app = builder.Build();
app.MapMagicOnionService();
app.Run();
I added AddScoped
for IRTCHub
(streaming hub interface; RTCHub
is the implementation of it) since the lifetime of RTCHub
is per connection.
For more information and context, I am attaching the code of MyProxy.cs
:
using System.Reflection;
namespace GrpcVehicle.Services
{
public class MyProxy<T> : DispatchProxy
{
private T? _decorated;
protected override object? Invoke(MethodInfo? targetMethod, object?[]? args)
{
Console.WriteLine("Invoke function is called!");
if (targetMethod is null || args == null)
{
return null;
}
Console.WriteLine($"Before executing {targetMethod.Name}");
foreach (var arg in args)
{
Console.WriteLine($"Arguments: {arg}");
}
var result = targetMethod.Invoke(_decorated, args);
Console.WriteLine($"After executing {targetMethod.Name}");
return result;
}
public static T Create(T decorated)
{
Console.WriteLine($"Creating proxy for {typeof(T).Name}");
object? proxy = Create<T, MyProxy<T>>();
if (proxy is MyProxy<T> myProxy)
{
myProxy._decorated = decorated;
return (T)proxy;
}
else
{
throw new InvalidOperationException("Proxy creation failed.");
}
}
}
}
There is nothing special but I put some Console.WriteLine()
in order to check whether this proxy function works properly.
The problem is that, as I mentioned before, once the client invokes one of the methods in IRTCHub
, it works as before; virtually it implies that my proxy thing is not registered and thus my intention is not working as expected.
I hope my description fulfils the requirement for your generous help. Thanks in advance 🙂