Files
52df519e50 Expose the client configuration provider and add an opt-in eager load on host start (#4343)
# Description

`AddClient(configurationFile)` (#4328) loads the supplied configuration
XML lazily on the first DI session connect, and the
`ClientSuppliedConfigurationProvider` behind it was reachable only
through internals. Hosted clients whose user interface needs the
`ApplicationConfiguration` **before any session exists** therefore had
no public way to trigger the load or to read the configuration back —
the concrete blocker for moving the 14 WinForms sample clients and the
GDS client off the classic eager `ApplicationInstance` path
(OPCFoundation/UA-.NETStandard-Samples#794 /
OPCFoundation/UA-.NETStandard-Samples#808).

Two small additions, exactly as designed in #4340:

**1. `OpcUaClientOptions.ConfigurationProvider` is now public** (`get`;
the setter stays `internal`).

It is already typed as the public
`IOpcUaApplicationConfigurationProvider`, so consumers get everything
they need with **no new types**: `GetAsync(ct)` as an explicit load
trigger that does not connect a session, `Configuration` for the loaded
document, and `Application` (`IApplicationInstance`) for the
applications that manage their own instance certificate. Registering the
supplied provider as `IOpcUaApplicationConfigurationProvider` in DI was
deliberately *not* done — `OpcUaServerHostedService` binds to the last
registered interface when it has no document of its own, so in a
combined client+server host a client-only document would silently
capture the server.

**2. `OpcUaClientOptions.LoadConfigurationOnStart` — an opt-in eager
load for hosted applications.**

It registers an internal `ClientConfigurationLoaderHostedService` that
awaits `GetAsync` during host start, the client-side twin of
`ReverseConnectManagerHostedService`. When `host.StartAsync()` returns,
the document is loaded and validated, the application-instance
certificate is ensured, `Configuration` is published onto the resolved
options (exactly as the connect path does), and a load failure fails the
host start instead of surfacing on the first connect. It is registered
ahead of the reverse-connect hosted service, so the configuration is
complete before anything consumes it.

The flag applies to every provider source — a document supplied via
`ConfigurationFile` / `ConfigurationStream` and a shared
`ConfigureApplication(...)` provider alike — and is a no-op for an
explicit `Configuration`, which is already complete. It is bindable from
`OpcUa:Client:LoadConfigurationOnStart`. Applications without a Generic
Host call `GetAsync` on the provider directly instead; both routes share
the provider's single-flight load, so the configuration is never loaded
twice.

A WinForms client then becomes:

```csharp
services.AddOpcUa().AddClient("MyClient.Config.xml", o => o.LoadConfigurationOnStart = true);

await host.StartAsync();

ApplicationConfiguration configuration = host.Services
    .GetRequiredService<OpcUaClientOptions>()
    .ConfigurationProvider!.Configuration;
```

**Reviewer note:** because the flag decides a *service registration*, it
must be set inside the `AddClient(...)` callback or bound from the
configuration section — setting it on the resolved options afterwards
has no effect. This is called out in the XML docs and in
`DependencyInjection.md`.

**Coverage:** three tests added to `ClientConfigurationFileTests` for
the supplied-document path (eager load on start including the
certificate bootstrap and `Application` surface, load failure surfacing
on start, no hosted service registered without the flag) and a new
`ClientEagerConfigurationLoadTests` fixture for the provider-agnostic
behavior (shared `ConfigureApplication(...)` provider awaited exactly
once, explicit-`Configuration` no-op, host-startup-token cancellation
aborting the load, configuration-section binding, and an end-to-end
`host.StartAsync()` test). All 331 `ClientBuilder` tests pass (8 new),
as do the 185 server hosting tests including the combined client+server
fixtures. `Opc.Ua.Client` builds warning-free on all target frameworks;
the test project builds clean on net10.0 and net472.

**Docs:** new "Client: loading the configuration eagerly" section in
`docs/DependencyInjection.md` and a pointer in the `Opc.Ua.Client` NuGet
README.

With these in place the sample clients can switch in a follow-up to
OPCFoundation/UA-.NETStandard-Samples#808.

## Related Issues

- Fixes #4340
- Builds on #4328

## Checklist

_Put an `x` in the boxes that apply. You can complete these step by step
after opening the PR._

- [x] I have signed the
[CLA](https://opcfoundation.org/license/cla/ContributorLicenseAgreementv1.0.pdf)
and read the
[CONTRIBUTING](https://github.com/OPCFoundation/UA-.NETStandard/blob/master/CONTRIBUTING.md)
doc.
- [x] I have added tests that prove my fix is effective or that my
feature works and increased code coverage.
- [x] I have added all necessary documentation.
- [x] I have verified that my changes do not introduce (new) build or
analyzer warnings.
- [ ] I ran **all** tests locally using the **UA.slnx** solution against
at least .net **framework** and .net **10**, and all passed.
- [ ] I fixed **all** failing and flaky tests in the CI pipelines and
**all** CodeQL warnings.
- [ ] I have addressed **all** PR feedback received.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Marc Schier <marcschier@users.noreply.github.com>
2026-08-30 20:50:46 +02:00

253 lines
10 KiB
C#

/* ========================================================================
* Copyright (c) 2005-2026 The OPC Foundation, Inc. All rights reserved.
*
* OPC Foundation MIT License 1.00
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* The complete license agreement can be found here:
* http://opcfoundation.org/License/MIT/1.00/
* ======================================================================*/
#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Memory;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Moq;
using NUnit.Framework;
using Opc.Ua.Configuration;
namespace Opc.Ua.Client.Tests.ClientBuilder
{
/// <summary>
/// Exercises the provider-agnostic part of the eager client
/// configuration load: the public
/// <see cref="OpcUaClientOptions.ConfigurationProvider"/> surface and
/// the <see cref="OpcUaClientOptions.LoadConfigurationOnStart"/> hosted
/// service that awaits
/// <see cref="IOpcUaApplicationConfigurationProvider.GetAsync"/> during
/// host start. The supplied-document (<c>AddClient(configurationFile)</c>)
/// cases live in <see cref="ClientConfigurationFileTests"/>.
/// </summary>
[TestFixture]
[Category("Client")]
[Category("ClientBuilder")]
[SetCulture("en-us")]
[SetUICulture("en-us")]
[Parallelizable]
public sealed class ClientEagerConfigurationLoadTests
{
[Test]
public async Task LoadConfigurationOnStartAwaitsSharedProviderAsync()
{
ApplicationConfiguration configuration = CreateConfiguration();
Mock<IOpcUaApplicationConfigurationProvider> configurationProvider =
CreateProviderMock(configuration);
var services = new ServiceCollection();
services.AddLogging();
services.AddSingleton(configurationProvider.Object);
services.AddOpcUa().AddClient(options => options.LoadConfigurationOnStart = true);
await using ServiceProvider provider = services.BuildServiceProvider();
OpcUaClientOptions options = provider.GetRequiredService<OpcUaClientOptions>();
// The shared provider is exposed publicly, so an application can
// load and read the configuration back without a session.
Assert.That(
options.ConfigurationProvider,
Is.SameAs(configurationProvider.Object));
IHostedService loader = GetLoader(provider);
await loader.StartAsync(CancellationToken.None).ConfigureAwait(false);
configurationProvider.Verify(
p => p.GetAsync(It.IsAny<CancellationToken>()),
Times.Once);
Assert.That(options.Configuration, Is.SameAs(configuration));
await loader.StopAsync(CancellationToken.None).ConfigureAwait(false);
}
[Test]
public async Task LoadConfigurationOnStartIsNoOpForExplicitConfigurationAsync()
{
ApplicationConfiguration configuration = CreateConfiguration();
var services = new ServiceCollection();
services.AddLogging();
services.AddOpcUa().AddClient(options =>
{
options.Configuration = configuration;
options.LoadConfigurationOnStart = true;
});
await using ServiceProvider provider = services.BuildServiceProvider();
OpcUaClientOptions options = provider.GetRequiredService<OpcUaClientOptions>();
// Nothing to load: an explicit configuration is already complete.
Assert.That(options.ConfigurationProvider, Is.Null);
IHostedService loader = GetLoader(provider);
Assert.That(
() => loader.StartAsync(CancellationToken.None),
Throws.Nothing);
Assert.That(options.Configuration, Is.SameAs(configuration));
}
[Test]
public async Task LoadConfigurationOnStartCancellationAbortsHostStartAsync()
{
ApplicationConfiguration configuration = CreateConfiguration();
var started = new TaskCompletionSource<bool>(
TaskCreationOptions.RunContinuationsAsynchronously);
var configurationProvider =
new Mock<IOpcUaApplicationConfigurationProvider>();
configurationProvider.Setup(p => p.Configuration).Returns(configuration);
configurationProvider
.Setup(p => p.GetAsync(It.IsAny<CancellationToken>()))
.Returns(async (CancellationToken ct) =>
{
started.TrySetResult(true);
await Task.Delay(Timeout.Infinite, ct).ConfigureAwait(false);
return configuration;
});
var services = new ServiceCollection();
services.AddLogging();
services.AddSingleton(configurationProvider.Object);
services.AddOpcUa().AddClient(options => options.LoadConfigurationOnStart = true);
await using ServiceProvider provider = services.BuildServiceProvider();
IHostedService loader = GetLoader(provider);
using var cts = new CancellationTokenSource();
Task start = loader.StartAsync(cts.Token);
await started.Task.ConfigureAwait(false);
cts.Cancel();
// The host's startup token is passed through to the load.
Assert.That(
async () => await start.ConfigureAwait(false),
Throws.InstanceOf<OperationCanceledException>());
}
[Test]
public async Task LoadConfigurationOnStartBindsFromConfigurationSectionAsync()
{
IConfiguration configurationRoot = new ConfigurationBuilder()
.Add(new MemoryConfigurationSource
{
InitialData = new Dictionary<string, string?>
{
["OpcUa:Client:LoadConfigurationOnStart"] = "true"
}
})
.Build();
var services = new ServiceCollection();
services.AddLogging();
services.AddSingleton(CreateProviderMock(CreateConfiguration()).Object);
services.AddOpcUa().AddClient(configurationRoot);
await using ServiceProvider provider = services.BuildServiceProvider();
Assert.That(
provider.GetRequiredService<OpcUaClientOptions>().LoadConfigurationOnStart,
Is.True);
Assert.That(GetLoader(provider), Is.Not.Null);
}
#if NET8_0_OR_GREATER
[Test]
public async Task HostStartAsyncCompletesTheConfigurationLoadAsync()
{
ApplicationConfiguration configuration = CreateConfiguration();
Mock<IOpcUaApplicationConfigurationProvider> configurationProvider =
CreateProviderMock(configuration);
using IHost host = new HostBuilder()
.ConfigureServices((_, services) =>
{
services.AddLogging();
services.AddSingleton(configurationProvider.Object);
services.AddOpcUa().AddClient(
options => options.LoadConfigurationOnStart = true);
})
.Build();
await host.StartAsync().ConfigureAwait(false);
try
{
// When StartAsync returns the configuration is loaded and
// readable through the public options surface, which is what
// user-interface hosts need before any session exists.
OpcUaClientOptions options =
host.Services.GetRequiredService<OpcUaClientOptions>();
Assert.That(
options.ConfigurationProvider!.Configuration,
Is.SameAs(configuration));
Assert.That(options.Configuration, Is.SameAs(configuration));
configurationProvider.Verify(
p => p.GetAsync(It.IsAny<CancellationToken>()),
Times.Once);
}
finally
{
await host.StopAsync().ConfigureAwait(false);
}
}
#endif
private static IHostedService GetLoader(IServiceProvider provider)
{
return provider.GetServices<IHostedService>()
.Single(service => service is ClientConfigurationLoaderHostedService);
}
private static Mock<IOpcUaApplicationConfigurationProvider> CreateProviderMock(
ApplicationConfiguration configuration)
{
var configurationProvider =
new Mock<IOpcUaApplicationConfigurationProvider>();
configurationProvider.Setup(p => p.Configuration).Returns(configuration);
configurationProvider
.Setup(p => p.GetAsync(It.IsAny<CancellationToken>()))
.ReturnsAsync(configuration);
return configurationProvider;
}
private static ApplicationConfiguration CreateConfiguration()
{
return new ApplicationConfiguration(
Opc.Ua.Tests.NUnitTelemetryContext.Create());
}
}
}