Class ClientBuilderBase<TClient> (4.2.0)

public abstract class ClientBuilderBase<TClient>

Base class for API-specific builders.

Inheritance

Object > ClientBuilderBase<TClient>

Namespace

Google.Api.Gax.Grpc

Assembly

Google.Api.Gax.Grpc.dll

Type Parameter

NameDescription
TClient

The type of client created by this builder.

Constructors

ClientBuilderBase(ServiceMetadata)

protected ClientBuilderBase(ServiceMetadata serviceMetadata)

Creates a new instance with no explicit settings. This takes the value of UseJwtAccessWithScopes from serviceMetadata.

Parameter
NameDescription
serviceMetadataServiceMetadata

The metadata for the service that the client will be used with. Must not be null.

Properties

CallInvoker

public CallInvoker CallInvoker { get; set; }

The call invoker to use, or null to create the call invoker when the client is built.

Property Value
TypeDescription
CallInvoker

CanUseChannelPool

protected virtual bool CanUseChannelPool { get; }

Returns whether or not a channel pool can be used if a channel is required. The default behavior is to return true if and only if no quota project, scopes, credentials or token access method have been specified and if UseJwtAccessWithScopes flag matches the flag in ChannelPool. Derived classes should override this property if there are other reasons why the channel pool should not be used.

Property Value
TypeDescription
Boolean

ChannelCredentials

public ChannelCredentials ChannelCredentials { get; set; }

The channel credentials to use, or null if credentials are being provided in a different way.

Property Value
TypeDescription
ChannelCredentials

Credential

public ICredential Credential { get; set; }

The credentials to use in "raw" form, for conversion into channel credentials. No other settings (e.g. QuotaProject or Scopes) are applied to these credentials.

Property Value
TypeDescription
ICredential

CredentialsPath

public string CredentialsPath { get; set; }

The path to the credentials file to use, or null if credentials are being provided in a different way.

Property Value
TypeDescription
String

DefaultOptions

protected static GrpcChannelOptions DefaultOptions { get; }

The default gRPC options.

Property Value
TypeDescription
GrpcChannelOptions

EffectiveGrpcAdapter

protected GrpcAdapter EffectiveGrpcAdapter { get; }

Returns the effective GrpcAdapter for this builder, using the GrpcAdapter property if that is set, or the appropriate fallback adapter for ServiceMetadata otherwise.

Property Value
TypeDescription
GrpcAdapter

EmulatorDetection

protected EmulatorDetection EmulatorDetection { get; set; }

The emulator detection policy to apply when building a client. Derived classes which support emulators should create public properties which delegate to this one. The default value is None.

Property Value
TypeDescription
EmulatorDetection

Endpoint

public string Endpoint { get; set; }

The endpoint to connect to, or null to use the default endpoint.

Property Value
TypeDescription
String

GoogleCredential

public GoogleCredential GoogleCredential { get; set; }

The credentials to use as a GoogleCredential, or null if credentials are being provided in a different way. Note that unlike ChannelCredentials and TokenAccessMethod, settings for Scopes, QuotaProject and self-signed JWTs will be applied to this credential (creating a new one), in the same way as for application default credentials and credentials specified using CredentialsPath or JsonCredentials.

Property Value
TypeDescription
GoogleCredential

GrpcAdapter

public GrpcAdapter GrpcAdapter { get; set; }

The gRPC implementation to use, or null to use the default implementation.

Property Value
TypeDescription
GrpcAdapter

GrpcChannelOptions

public GrpcChannelOptions GrpcChannelOptions { get; set; }

Any custom channel options to merge with the default options. If an option specified both here and in the default options, the custom option will take priority. This property may be null (the default) in which case the default options are used.

Property Value
TypeDescription
GrpcChannelOptions

JsonCredentials

public string JsonCredentials { get; set; }

The credentials to use as a JSON string, or null if credentials are being provided in a different way.

Property Value
TypeDescription
String

LastCreatedChannel

public ChannelBase LastCreatedChannel { get; protected set; }

Returns the channel created last time any of the Build()-related methods were called, or

null
if the last-created client did not require channel creation. If a channel is obtained from a channel pool, this does not count as channel creation. This property is useful when multiple clients are created and the calling code wishes to clean up resources associated with the channel.

Property Value
TypeDescription
ChannelBase

Logger

public ILogger Logger { get; set; }

The logger to include in the client, if any.

Property Value
TypeDescription
ILogger

QuotaProject

public string QuotaProject { get; set; }

The GCP project ID that should be used for quota and billing purposes. May be null.

Property Value
TypeDescription
String

Scopes

public IReadOnlyList<string> Scopes { get; set; }

The scopes to use, or null to use the default scopes.

Property Value
TypeDescription
IReadOnlyList<String>

ServiceMetadata

protected ServiceMetadata ServiceMetadata { get; }

The metadata associated with the service that this client will make requests to.

Property Value
TypeDescription
ServiceMetadata

TokenAccessMethod

[Obsolete("The Credential property is preferred for simplicity. This property may be removed in a future major version.")]
public Func<string, CancellationToken, Task<string>> TokenAccessMethod { get; set; }

The token access method to use, or null if credentials are being provided in a different way.

Property Value
TypeDescription
Func<String, CancellationToken, Task<String>>

UseJwtAccessWithScopes

public bool UseJwtAccessWithScopes { get; set; }

Returns whether or not self-signed JWTs will be used over OAuth tokens when OAuth scopes are explicitly set.

Property Value
TypeDescription
Boolean
Remarks

In the base implementation, this defaults to true. Subclasses may add code in their own constructors to make the default effectively false, however.

UserAgent

public string UserAgent { get; set; }

A custom user agent to specify in the channel metadata, or null if no custom user agent is required.

Property Value
TypeDescription
String

Methods

Build()

public abstract TClient Build()

Builds the resulting client.

Returns
TypeDescription
TClient

Build(IServiceProvider)

public TClient Build(IServiceProvider provider)

Populates properties supplied via dependency injection, then builds a client.

Parameter
NameDescription
providerIServiceProvider

The service provider to request dependencies from. Must not be null.

Returns
TypeDescription
TClient

An API client configured from this builder.

BuildAsync(IServiceProvider, CancellationToken)

public async Task<TClient> BuildAsync(IServiceProvider provider, CancellationToken cancellationToken = default(CancellationToken))

Populates properties supplied via dependency injection, then builds a client asynchronously.

Parameters
NameDescription
providerIServiceProvider

The service provider to request dependencies from. Must not be null.

cancellationTokenCancellationToken

A token to cancel the operation.

Returns
TypeDescription
Task<TClient>

An API client configured from this builder.

BuildAsync(CancellationToken)

public abstract Task<TClient> BuildAsync(CancellationToken cancellationToken = default(CancellationToken))

Builds the resulting client asynchronously.

Parameter
NameDescription
cancellationTokenCancellationToken
Returns
TypeDescription
Task<TClient>

Configure(IServiceProvider)

protected virtual void Configure(IServiceProvider provider)

Populates properties based on those set via dependency injection.

Parameter
NameDescription
providerIServiceProvider

The service provider to request dependencies from.

Remarks

If gRPC adapters are configured in provider, the first one that supports the ServiceMetadata will be used.

Credentials are only requested from dependency injection if they are not already set via any of ChannelCredentials, CredentialsPath, JsonCredentials, Credential, GoogleCredential or TokenAccessMethod.

If credentials are requested, they are tried in the following order:

  • ChannelCredentials
  • ICredential
  • GoogleCredential

CopyCommonSettings<TOther>(ClientBuilderBase<TOther>)

protected void CopyCommonSettings<TOther>(ClientBuilderBase<TOther> source)

Copies common settings from the specified builder into this one. This is a shallow copy.

Parameter
NameDescription
sourceClientBuilderBase<TOther>

The builder to copy from.

Type Parameter
NameDescription
TOther

The other client type

CopySettingsForEmulator(ClientBuilderBase<TClient>)

protected void CopySettingsForEmulator(ClientBuilderBase<TClient> source)

Copies common settings from the specified builder, expecting that any settings around credentials and endpoints will be set by the caller, along with any client-specific settings. Emulator detection is not copied, to avoid infinite recursion when building.

Parameter
NameDescription
sourceClientBuilderBase<TClient>

CreateCallInvoker()

protected virtual CallInvoker CreateCallInvoker()

Creates a call invoker synchronously. Override this method in a concrete builder type if more call invoker mechanisms are supported. This implementation calls GetChannelCredentials() if no call invoker is specified.

Returns
TypeDescription
CallInvoker

CreateCallInvokerAsync(CancellationToken)

protected virtual async Task<CallInvoker> CreateCallInvokerAsync(CancellationToken cancellationToken)

Creates a call invoker asynchronously. Override this method in a concrete builder type if more call invoker mechanisms are supported. This implementation calls GetChannelCredentialsAsync(CancellationToken) if no call invoker is specified.

Parameter
NameDescription
cancellationTokenCancellationToken
Returns
TypeDescription
Task<CallInvoker>

CreateChannel(String, ChannelCredentials)

protected virtual ChannelBase CreateChannel(string endpoint, ChannelCredentials credentials)

Returns a as created by EffectiveGrpcAdapter for the specified endpoint and credentials, using the gRPC channel options from GetChannelOptions().

Parameters
NameDescription
endpointString

The endpoint of the channel.

credentialsChannelCredentials

The channel credentials.

Returns
TypeDescription
ChannelBase

The channel created by the gRPC adapter.

Remarks

This is only useful in very specific situations where a known channel is required; CreateCallInvoker() and its async equivalent are more usually useful. This implementation sets the LastCreatedChannel property, and so should any overriding implementations.

GetChannelCredentials()

protected virtual ChannelCredentials GetChannelCredentials()

Obtains channel credentials synchronously. Override this method in a concrete builder type if more credential mechanisms are supported.

Returns
TypeDescription
ChannelCredentials

GetChannelCredentialsAsync(CancellationToken)

protected virtual async Task<ChannelCredentials> GetChannelCredentialsAsync(CancellationToken cancellationToken)

Obtains channel credentials asynchronously. Override this method in a concrete builder type if more credential mechanisms are supported.

Parameter
NameDescription
cancellationTokenCancellationToken
Returns
TypeDescription
Task<ChannelCredentials>

GetChannelOptions()

protected virtual GrpcChannelOptions GetChannelOptions()

Returns the options to use when creating a channel, taking GrpcChannelOptions into account.

Returns
TypeDescription
GrpcChannelOptions

The options to use when creating a channel.

GetChannelPool()

protected abstract ChannelPool GetChannelPool()

Returns the channel pool to use when no other options are specified. This method is not called unless CanUseChannelPool returns true, so if a channel pool is unavailable, override that property to return false and throw an exception from this method.

Returns
TypeDescription
ChannelPool

GetEmulatorEnvironment(IEnumerable<String>, IEnumerable<String>, Func<String, String>)

protected Dictionary<string, string> GetEmulatorEnvironment(IEnumerable<string> requiredEmulatorEnvironmentVariables, IEnumerable<string> allEmulatorEnvironmentVariables, Func<string, string> environmentVariableProvider = null)

Performs basic emulator detection and validation based on the given environment variables. This method is expected to be called by a derived class that supports emulators, in order to perform the common work of checking whether the emulator is configured in the environment.

Parameters
NameDescription
requiredEmulatorEnvironmentVariablesIEnumerable<String>

Required emulator environment variables.

allEmulatorEnvironmentVariablesIEnumerable<String>

All emulator environment variables.

environmentVariableProviderFunc<String, String>

The provider used to retrieve environment variables. This is used to faciliate testing, and defaults to using GetEnvironmentVariable(String).

Returns
TypeDescription
Dictionary<String, String>

A key/value mapping of the emulator environment variables to their values, or null if the emulator should not be used.

Remarks

If the emulator should not be used, either due to being disabled in EmulatorDetection or the appropriate environment variables not being set, this method returns null.

Otherwise, a dictionary is returned mapping every value in allEmulatorEnvironmentVariables to the value in the environment. Any missing, empty or whitespace-only values are mapped to a null reference in the returned dictionary, but the entry will still be present (so callers can use an indexer with the returned dictionary for every environment variable passed in).

Exceptions
TypeDescription
InvalidOperationException

The configuration is inconsistent, e.g. due to some environment variables being set but not all the required ones, or any environment variables being set in a production-only environment.

Validate()

protected virtual void Validate()

Validates that the builder is in a consistent state for building. For example, it's invalid to call Build() on an instance which has both JSON credentials and a credentials path specified.

Exceptions
TypeDescription
InvalidOperationException

The builder is in an invalid state.

ValidateAtMostOneNotNull(String, Object[])

protected void ValidateAtMostOneNotNull(string message, params object[] values)

Validates that at most one of the given values is not null.

Parameters
NameDescription
messageString

The message if the condition is violated.

valuesObject[]

The values to check for nullity.

Exceptions
TypeDescription
InvalidOperationException

More than one value is null.

ValidateOptionExcludesOthers(String, Object, Object[])

protected void ValidateOptionExcludesOthers(string message, object controlling, params object[] values)

Validates that if controlling is not null, then every value in values is null.

Parameters
NameDescription
messageString

The message if the condition is violated.

controllingObject

The value controlling whether or not any other value can be non-null.

valuesObject[]

The values checked for non-nullity if controlling is non-null.