ISB002 Avoid storing rentals in fields
Proxies obtained from ServiceBrokerClient.GetProxyAsync<T> should be used and disposed of within a single async method.
This allows the ServiceBrokerClient to manage proxy lifetimes.
If proxies need to be held for longer than an async method, use the IServiceBroker interface instead of ServiceBrokerClient.
Examples of patterns that are flagged by this analyzer
The following code acquires and uses a proxy to a brokered service and stores the rental in a field. This generates a diagnostic.
class Foo
{
ServiceBrokerClient serviceBrokerClient;
ServiceBrokerClient.Rental<IMyService> proxyRental;
async Task DoSomethingAsync()
{
proxyRental = await serviceBrokerClient.GetProxyAsync<IMyService>(someDescriptor);
}
}
Solution
Fix the error by using the rental only within the async method:
class Foo
{
ServiceBrokerClient serviceBrokerClient;
async Task DoSomethingAsync()
{
using (var proxyRental = await serviceBrokerClient.GetProxyAsync<IMyService>(someDescriptor))
{
if (proxyRental.Proxy is object)
{
// use proxyRental.Proxy here
}
}
}
}
Or if you need to manage the proxy lifetime beyond the async method, use IServiceBroker instead:
class Foo : IDisposable
{
IServiceBroker serviceBroker;
IMyService? proxy;
async Task DoSomethingAsync()
{
if (proxy is null)
{
proxy = await serviceBroker.GetProxyAsync<IMyService>(someDescriptor);
}
if (proxy is object)
{
// use proxy here
}
}
public void Dispose() => (proxy as IDisposable)?.Dispose();
}