NBJSONRPC005: Do not store service rentals in fields or properties
| Property | Value |
|---|---|
| ID | NBJSONRPC005 |
| Category | Usage |
| Default severity | Warning |
Rentals obtained from ServiceBrokerClient.GetProxyAsync should be used and disposed of within the acquiring asynchronous method.
Storing a rental in a field or property extends its lifetime beyond that scope and interferes with timely cache invalidation and service replacement.
This rule also diagnoses storing an existing local rental or storing a rental through a conversion to object.
Avoid storing the rental:
this.rental = await client.GetProxyAsync(BrokeredServiceExamples.Greeter, cancellationToken: cancellationToken);
Instead, keep it local:
using ServiceBrokerClient client = new(broker);
using ServiceBrokerClient.Rental<IGreeter> rental = await client.GetProxyAsync(Greeter, cancellationToken: cancellationToken);
IGreeter greeter = rental.Proxy ?? throw new InvalidOperationException("The greeting service is unavailable.");
return await greeter.GreetAsync("Ada", cancellationToken);
For longer-lived service ownership, acquire the proxy directly from IServiceBroker and follow NBJSONRPC004. No automatic code fix is offered because moving a rental changes its lifetime and may require redesigning its owner. Suppress this diagnostic only when deliberately retaining a rental, and ensure it is disposed. This rule is the Nerdbank.JsonRpc counterpart of ServiceHub's ISB002.