Dependency Injection Role
An RPC service should not use a lengthy hardcoded switch statement to choose a request handler. The common approach is to register handler types against method names with a dependency injection mechanism, and then later rely on it to construct the selected handler according to the method name received in the request. For example, the following registry maps method names to handler types:
Method Name Handler Type ------------------- -------------------------------------- Bank.MakeDeposit -> BankMakeDepositHandler Shipment.Search -> ShipmentSearchHandler
All request handlers are supposed to implement a common interface, say IRpcRequestHandler, which defines a method that takes a request object and returns a response object. For example:
public interface IRpcRequestHandler
{
Task<object?> HandleAsync(object? request, CancellationToken cancellationToken);
}
Then we can register these handlers with a dependency injection:
var builder = WebApplication.CreateBuilder(args); builder.Services.AddKeyedScoped("Bank.MakeDeposit"); builder.Services.AddKeyedScoped ("Shipment.Search");
When a request comes in with method name, say Bank.MakeDeposit, the dispatcher can ask the dependency injection to resolve the corresponding handler type, which is BankMakeDepositHandler in this case. The DI will create an instance of that handler, injecting any dependencies it needs, and call its HandleAsync method to process the request, like this:
IRpcRequestHandler? handler = _serviceProvider.GetKeyedService(request.Method); object? result = await handler.HandleAsync(request.Params); return JsonRpcResponse.CreateResult(request.Id, result);
Dependency injection helps separate infrastructure concerns from business logic. The RPC endpoint remains focused on dispatching, while handlers remain focused on business operations.
Table of Content Operation-Oriented APIs and AI Tools Previous: Single Endpoint Architecture Next: One Operation, One Handler
Business Process Programming in .Net
© 2004–2026 Laskarzhevsky Software Inc.
Unless otherwise noted, the content of this website is licensed under the
Creative Commons Attribution 4.0 International License (CC BY 4.0).
Code examples are provided under the MIT License.
You are free to share and adapt the material provided that appropriate
credit is given and any modifications are clearly indicated.
The information provided on this website is for educational purposes only.
The author and publisher make no warranties regarding the completeness
or suitability of the information and are not responsible for any damages
resulting from its use.