
Azure SDK clients fit dependency injection well. They are thread-safe, designed for reuse and already own authentication, retries, diagnostics, HTTP connections or AMQP connections.
That does not mean every application handler should inject BlobClient, SecretClient or ServiceBusSender directly.
The design uses two boundaries:
- Infrastructure registers and reuses the actual Azure SDK clients.
- Application code depends on a small capability such as
IReportArchiveorIOrderDispatchQueue.
Dependency injection answers who constructs an object. The application interface answers which external concepts a layer is allowed to know. Those are different problems.
Direct client injection still spreads Azure
This handler uses constructor injection but remains fully coupled to Blob Storage:
1using Azure;
2using Azure.Storage.Blobs;
3using Azure.Storage.Blobs.Models;
4
5public sealed class PublishReportHandler
6{
7 private readonly BlobContainerClient _containerClient;
8
9 public PublishReportHandler(BlobContainerClient containerClient)
10 {
11 _containerClient = containerClient;
12 }
13
14 public async Task PublishAsync(
15 Guid reportId,
16 Stream content,
17 CancellationToken cancellationToken)
18 {
19 BlobClient blobClient = _containerClient.GetBlobClient(
20 $"{reportId:N}.pdf");
21
22 BlobUploadOptions uploadOptions = new BlobUploadOptions
23 {
24 HttpHeaders = new BlobHttpHeaders
25 {
26 ContentType = "application/pdf"
27 },
28 Conditions = new BlobRequestConditions
29 {
30 IfNoneMatch = ETag.All
31 }
32 };
33
34 await blobClient.UploadAsync(
35 content,
36 uploadOptions,
37 cancellationToken);
38 }
39}The handler now owns blob naming, content headers, ETags, conditional-write semantics, SDK overloads, response wrappers and RequestFailedException. Its tests must speak the same infrastructure language.
That code is an Azure adapter inside an application handler. DI made construction replaceable; it did not make the dependency narrow.
Reuse real SDK clients
Top-level Azure clients should normally be reused across requests. Recreating credentials can fragment token caches and recreating clients repeats pipeline setup. HTTP-based clients share their default transport, so a new client does not necessarily create a new connection pool; Service Bus clients and senders have separate AMQP connection and link costs. For a deterministic, passwordless authentication setup, see Managed Identity in .NET: Stop Using Connection Strings .
Top-level clients are normally singleton or otherwise long-lived. Stateless adapters over them can also be singleton. Mutable request models and options are different: client thread safety does not imply that every model object can be shared across requests.
Microsoft.Extensions.Azure owns credential, endpoint, client options, named clients, lifetime and logging integration in the composition root.
Define the application capability first
A weak wrapper copies the SDK:
1public interface IBlobClient
2{
3 Task<Response<BlobContentInfo>> UploadAsync(
4 Stream content,
5 BlobUploadOptions options,
6 CancellationToken cancellationToken);
7}It still exposes Azure types and changes with Azure signatures. The only achievement is making a virtual method look like an interface.
A useful port expresses application behavior:
1public readonly record struct ReportId(Guid Value)
2{
3 public override string ToString() => Value.ToString("N");
4}
5
6public sealed record ReportDocument(
7 ReportId Id,
8 Stream Content,
9 string ContentType);
10
11public enum StoreReportOutcome
12{
13 Stored,
14 AlreadyExists
15}
16
17public sealed record StoreReportResult(
18 StoreReportOutcome Outcome,
19 string? Version);
20
21public interface IReportArchive
22{
23 Task<StoreReportResult> StoreAsync(
24 ReportDocument document,
25 CancellationToken cancellationToken);
26}This contract decides that storage is create-only, duplicates are expected, content remains streamed, content type matters, version is opaque and cancellation propagates.
The caller owns the stream; the adapter reads from its current position and does not dispose it. Stream ownership belongs in the contract because it cannot be inferred from Stream alone.
The version exists only because application behavior may need it. ETags should not cross every layer “just in case.”
The Azure adapter owns Azure semantics
1using System.Net;
2using Azure;
3using Azure.Storage.Blobs;
4using Azure.Storage.Blobs.Models;
5
6public sealed class AzureBlobReportArchive : IReportArchive
7{
8 private readonly BlobContainerClient _containerClient;
9
10 public AzureBlobReportArchive(
11 BlobContainerClient containerClient)
12 {
13 _containerClient = containerClient;
14 }
15
16 public async Task<StoreReportResult> StoreAsync(
17 ReportDocument document,
18 CancellationToken cancellationToken)
19 {
20 ArgumentNullException.ThrowIfNull(document);
21
22 string blobName = $"{document.Id}.pdf";
23 BlobClient blobClient =
24 _containerClient.GetBlobClient(blobName);
25
26 BlobUploadOptions uploadOptions = new BlobUploadOptions
27 {
28 HttpHeaders = new BlobHttpHeaders
29 {
30 ContentType = document.ContentType
31 },
32 Conditions = new BlobRequestConditions
33 {
34 IfNoneMatch = ETag.All
35 }
36 };
37
38 try
39 {
40 Response<BlobContentInfo> response =
41 await blobClient.UploadAsync(
42 document.Content,
43 uploadOptions,
44 cancellationToken);
45
46 return new StoreReportResult(
47 StoreReportOutcome.Stored,
48 response.Value.ETag.ToString());
49 }
50 catch (RequestFailedException exception)
51 when ((exception.Status == 412 &&
52 exception.ErrorCode == BlobErrorCode.ConditionNotMet.ToString()) ||
53 (exception.Status == 409 &&
54 exception.ErrorCode == BlobErrorCode.BlobAlreadyExists.ToString()))
55 {
56 return new StoreReportResult(
57 StoreReportOutcome.AlreadyExists,
58 Version: null);
59 }
60 catch (RequestFailedException exception)
61 {
62 throw CreateArchiveException(exception);
63 }
64 }
65
66 private static ReportArchiveException CreateArchiveException(
67 RequestFailedException exception)
68 {
69 HttpStatusCode statusCode =
70 (HttpStatusCode)exception.Status;
71
72 ReportArchiveFailure failure = statusCode switch
73 {
74 HttpStatusCode.Unauthorized or
75 HttpStatusCode.Forbidden =>
76 ReportArchiveFailure.AccessDenied,
77
78 HttpStatusCode.RequestTimeout or
79 HttpStatusCode.TooManyRequests =>
80 ReportArchiveFailure.Unavailable,
81
82 HttpStatusCode.BadRequest =>
83 ReportArchiveFailure.InvalidRequest,
84
85 _ when exception.Status >= 500 =>
86 ReportArchiveFailure.Unavailable,
87
88 _ => ReportArchiveFailure.Unexpected
89 };
90
91 return new ReportArchiveException(
92 failure,
93 "The report archive operation failed.",
94 exception);
95 }
96}IfNoneMatch = ETag.All makes create-only storage atomic. Checking ExistsAsync before upload would introduce a race.
For this create-only request, 412 with ConditionNotMet or 409 with BlobAlreadyExists becomes AlreadyExists. The precise service error can depend on the upload path. Other conflicts and precondition errors, such as lease failures, must not be reported as duplicates. Exhausted infrastructure failures become a small application-owned category:
1public enum ReportArchiveFailure
2{
3 AccessDenied,
4 Unavailable,
5 InvalidRequest,
6 Unexpected
7}
8
9public sealed class ReportArchiveException : Exception
10{
11 public ReportArchiveException(
12 ReportArchiveFailure failure,
13 string message,
14 Exception innerException)
15 : base(message, innerException)
16 {
17 Failure = failure;
18 }
19
20 public ReportArchiveFailure Failure { get; }
21}The inner RequestFailedException keeps service status, error code, request ID and diagnostics for logs. The outer contract remains stable and contains no Azure dependency.
Translation is useful only when application behavior needs a stable category. If every infrastructure exception reaches one generic failure boundary, preserving the original exception can be simpler.
Project ownership points inward
In a layered solution, the application project owns IReportArchive and its types. The Azure infrastructure project references the application and implements the port. The host references both and composes them.
1Web API -> Application
2 |
3 +----> Infrastructure.Azure -> ApplicationApplication has no Azure package reference. Putting the interface beside the implementation in Infrastructure would force the application to reference the layer it is meant to abstract.
A small service can express the same boundary with namespaces and folders. Project count is not the goal; enforceable dependency direction is.
Register client and adapter separately
1using Azure.Core;
2using Azure.Identity;
3using Azure.Storage.Blobs;
4using Microsoft.Extensions.Azure;
5using Microsoft.Extensions.Options;
6
7public sealed class ReportArchiveOptions
8{
9 public const string SectionName = "ReportArchive";
10
11 public required Uri ServiceUri { get; init; }
12
13 public required string ContainerName { get; init; }
14}
15
16public static class ReportArchiveRegistration
17{
18 public static IServiceCollection AddReportArchive(
19 this IServiceCollection services,
20 IConfiguration configuration,
21 IHostEnvironment hostEnvironment)
22 {
23 services
24 .AddOptions<ReportArchiveOptions>()
25 .Bind(configuration.GetRequiredSection(
26 ReportArchiveOptions.SectionName))
27 .Validate(
28 (ReportArchiveOptions options) =>
29 options.ServiceUri is { IsAbsoluteUri: true } &&
30 options.ServiceUri.Scheme == Uri.UriSchemeHttps,
31 "ReportArchive:ServiceUri must be an absolute HTTPS URI.")
32 .Validate(
33 (ReportArchiveOptions options) =>
34 !string.IsNullOrWhiteSpace(options.ContainerName),
35 "ReportArchive:ContainerName is required.")
36 .ValidateOnStart();
37
38 ReportArchiveOptions archiveOptions = configuration
39 .GetRequiredSection(ReportArchiveOptions.SectionName)
40 .Get<ReportArchiveOptions>()
41 ?? throw new InvalidOperationException(
42 "Report archive configuration is missing.");
43
44 TokenCredential credential = hostEnvironment.IsDevelopment()
45 ? new AzureCliCredential()
46 : new ManagedIdentityCredential(
47 ManagedIdentityId.SystemAssigned);
48
49 services.AddSingleton(credential);
50
51 services.AddAzureClients(
52 (AzureClientFactoryBuilder clientBuilder) =>
53 {
54 clientBuilder.UseCredential(credential);
55 clientBuilder.AddBlobServiceClient(
56 archiveOptions.ServiceUri);
57 });
58
59 services.AddSingleton<BlobContainerClient>(
60 (IServiceProvider serviceProvider) =>
61 {
62 BlobServiceClient serviceClient = serviceProvider
63 .GetRequiredService<BlobServiceClient>();
64
65 IOptions<ReportArchiveOptions> options = serviceProvider
66 .GetRequiredService<IOptions<ReportArchiveOptions>>();
67
68 return serviceClient.GetBlobContainerClient(
69 options.Value.ContainerName);
70 });
71
72 services.AddSingleton<IReportArchive, AzureBlobReportArchive>();
73
74 return services;
75 }
76}The fixed container subclient is reused. Individual blob clients remain cheap and are created on demand; registering one service for every blob ID would create an unbounded container.
Infrastructure creates the container and assigns its data-plane role before application traffic. The request path should not require administrative permissions.
Named Azure clients remain a composition detail when several accounts or namespaces use the same SDK type. IAzureClientFactory<BlobServiceClient> can select reports or audit while application handlers continue to depend on IReportArchive or IAuditArchive.
Messaging needs the same boundary
The application wants to enqueue a command, not construct AMQP metadata:
1public interface IOrderDispatchQueue
2{
3 Task EnqueueAsync(
4 OrderDispatch command,
5 CancellationToken cancellationToken);
6}The adapter owns serialization, message ID, subject and Service Bus types:
1using System.Text.Json;
2using Azure.Messaging.ServiceBus;
3
4public sealed class ServiceBusOrderDispatchQueue : IOrderDispatchQueue
5{
6 private readonly ServiceBusSender _sender;
7 private readonly JsonSerializerOptions _serializerOptions;
8
9 public ServiceBusOrderDispatchQueue(
10 ServiceBusSender sender,
11 JsonSerializerOptions serializerOptions)
12 {
13 _sender = sender;
14 _serializerOptions = serializerOptions;
15 }
16
17 public async Task EnqueueAsync(
18 OrderDispatch command,
19 CancellationToken cancellationToken)
20 {
21 BinaryData body = BinaryData.FromObjectAsJson(
22 command,
23 _serializerOptions);
24
25 ServiceBusMessage message = new ServiceBusMessage(body)
26 {
27 ContentType = "application/json",
28 MessageId = command.OrderId.ToString(),
29 Subject = "order.dispatch.v1"
30 };
31
32 await _sender.SendMessageAsync(message, cancellationToken);
33 }
34}ServiceBusClient, senders, receivers and processors are long-lived. Creating a sender per message loses AMQP connection and link reuse.
MessageId enables broker deduplication only when duplicate detection is configured on the entity and only within its configured history window. Using OrderId assumes exactly one logical dispatch command per order. If redispatch is valid, the command needs its own stable operation ID, reused for retries of that command.
Test application behavior without Azure types
The handler now talks only in application concepts:
1public sealed class PublishReportHandler
2{
3 private readonly IReportArchive _archive;
4 private readonly IReportPublicationNotifier _notifier;
5
6 public PublishReportHandler(
7 IReportArchive archive,
8 IReportPublicationNotifier notifier)
9 {
10 _archive = archive;
11 _notifier = notifier;
12 }
13
14 public async Task<PublishReportOutcome> HandleAsync(
15 PublishReport command,
16 CancellationToken cancellationToken)
17 {
18 ReportDocument document = new ReportDocument(
19 command.ReportId,
20 command.Content,
21 command.ContentType);
22
23 StoreReportResult result = await _archive.StoreAsync(
24 document,
25 cancellationToken);
26
27 if (result.Outcome == StoreReportOutcome.AlreadyExists)
28 {
29 return PublishReportOutcome.AlreadyPublished;
30 }
31
32 ReportPublished notification = new ReportPublished(
33 command.ReportId,
34 result.Version);
35
36 await _notifier.NotifyAsync(
37 notification,
38 cancellationToken);
39
40 return PublishReportOutcome.Published;
41 }
42}An NSubstitute test verifies publication behavior and cancellation propagation without Response<T>, ETags or model factories. The duplicate case verifies that no event is sent.
This handler demonstrates the dependency boundary, not durable publication. If storage succeeds and notification fails, a retry returns AlreadyPublished without sending the missing notification. A production workflow must persist publication progress and retry notification independently, typically through a durable workflow or an outbox in an authoritative transactional store. Blob Storage and Service Bus do not share a transaction and an existing blob alone does not prove that publication completed.
These tests survive an SDK upgrade because they describe application behavior. They would also survive replacing Blob Storage if the new archive honors the same create-only contract.
Test Azure translation where Azure belongs
Azure SDK clients are intentionally mockable: public service methods and subclient factories are virtual, protected constructors support test doubles and model factories create output-only models.
Those facilities belong in adapter tests that verify blob naming, content type, IfNoneMatch, ETag mapping, duplicate translation and failure categorization.
1using Azure;
2using Azure.Storage.Blobs;
3using Azure.Storage.Blobs.Models;
4using NSubstitute;
5
6BlobContainerClient containerClient =
7 Substitute.For<BlobContainerClient>();
8BlobClient blobClient = Substitute.For<BlobClient>();
9
10containerClient
11 .GetBlobClient("f96387322a1c49398266672f53f23f26.pdf")
12 .Returns(blobClient);
13
14BlobContentInfo contentInfo = BlobsModelFactory.BlobContentInfo(
15 eTag: new ETag("\"version-7\""),
16 lastModified: DateTimeOffset.UnixEpoch,
17 contentHash: Array.Empty<byte>(),
18 versionId: "version-7",
19 encryptionKeySha256: null,
20 encryptionScope: null,
21 blobSequenceNumber: 0);
22
23Response<BlobContentInfo> response = Response.FromValue(
24 contentInfo,
25 Substitute.For<Response>());The Azure-specific setup stays in one test suite. Repeating it across application tests would signal that the infrastructure boundary has leaked.
A mock proves how the adapter calls the SDK. It cannot prove Blob Storage’s real conditional status, identity, RBAC, network route, retry behavior or serialization. Those remain integration tests.
Four test layers have four jobs
| Layer | Dependency | Purpose |
|---|---|---|
| Application unit test | Mock or fake application port | Business branching and orchestration |
| Adapter unit test | Mocked client or test transport | SDK mapping and error translation |
| Local integration | Emulator or container | Protocol and state behavior |
| Azure integration | Real service | Identity, RBAC, network and service contract |
An in-memory fake is useful for stateful component tests when it honors the port’s create-only semantics. It does not emulate ETags, throttling, consistency, service limits or network faults and must never become a production fallback.
When generated HTTP requests matter, a custom Azure SDK transport can exercise the real client pipeline without network access. That remains an adapter-focused test, not a replacement for a live service.
Integration tests resolve IReportArchive from the real application container. Resolving BlobClient directly would bypass the production boundary the test is meant to verify.
Do not abstract away important semantics
Vendor independence is not semantic ambiguity. A port still states create-only versus overwrite, consistency, idempotency, payload limits, ordering, delivery guarantees, optimistic concurrency, retention and stream ownership.
If the application needs optimistic concurrency, it receives an application version token. If it needs message ordering, the queue port exposes an ordering key. A generic IStorageService.SaveAsync(string, object) hides too much to be useful.
Capability names stay concrete: IReportArchive, IOrderDispatchQueue, ICustomerDocumentReader or IFeatureSnapshotStore.
Keep paging and operations application-owned
Passing AsyncPageable<T> through a port hides remote page calls inside enumeration and couples continuation behavior to Azure.
1public sealed record ReportArchivePage(
2 IReadOnlyList<ArchivedReportSummary> Items,
3 string? ContinuationToken);
4
5public interface IReportArchiveReader
6{
7 Task<ReportArchivePage> GetPageAsync(
8 int pageSize,
9 string? continuationToken,
10 CancellationToken cancellationToken);
11}The continuation token remains opaque and bounded. An explicit page size makes network cost visible.
Similarly, Operation<T> should not become durable workflow state. The adapter starts the Azure long-running operation and returns an application operation ID. Later calls restore or query it. This makes process restarts and persistence explicit.
Retry ownership must not multiply
Azure SDK clients already retry documented transient transport and service failures. Three SDK attempts inside three application attempts create up to nine service calls, before broker redelivery is considered.
The ownership model is:
- SDK retry handles short transport and service transients.
- The adapter classifies exhausted infrastructure failure.
- Application retry exists only when the complete operation is idempotent and another attempt has business meaning.
- Broker redelivery handles durable workflow recovery.
Cancellation passes through every layer and is never translated into an infrastructure failure.
Observability has two levels
The Azure SDK already emits dependency traces, retries, request IDs and diagnostic logs. The adapter adds business context that the SDK cannot know: report.archive.store, bounded outcome, report class, complete duration and translated failure category.
Tracing should preserve this hierarchy:
1HTTP request
2 -> publish report handler
3 -> report archive adapter
4 -> Azure.Storage.Blobs dependencyThe adapter does not duplicate every HTTP event. Payloads, bearer tokens, account keys, SAS values, secrets and high-cardinality blob names stay out of telemetry by default.
Migration sequence
- Find Azure namespaces in controllers, handlers, domain services and application libraries.
- Group calls by application capability rather than SDK method.
- Define outcomes, idempotency, versioning, paging and ownership first.
- Move naming, serialization, conditions and exception mapping into one adapter.
- Keep SDK clients long-lived and resource selection in composition.
- Rewrite application tests against the port.
- Add focused adapter tests and retain live Azure tests.
- Remove Azure package references from application projects and enforce the direction.
This often removes code from handlers even though one adapter is added. The complexity already existed; it now has an owner.
Where additional interfaces stop helping
No extra port is needed when code already is the infrastructure adapter, a one-off administrative tool intentionally uses Azure-native semantics or a wrapper would mirror every SDK method unchanged.
The boundary is justified when application rules branch on external outcomes, several handlers share the capability, Azure models leak inward, tests repeatedly construct SDK wrappers, naming or serialization needs one owner or least-privilege capability should be explicit.
The objective is not maximum indirection. It is a narrow, honest dependency.
Design rule
Azure SDK clients are good infrastructure dependencies. They should be registered once, reused and allowed to own connections, token caches, retries and diagnostics.
Application code gets a different abstraction because it has a different vocabulary. IReportArchive expresses create-only report storage; IBlobClient merely copies Azure. That distinction centralizes vendor mechanics in one adapter and lets business tests describe business behavior.
Dependency injection done right is therefore two decisions: construct the Azure client correctly, then prevent that client from becoming the application architecture.
Further reading
- Azure SDK dependency injection for .NET
- Azure SDK guidance for ASP.NET Core
- Unit testing and mocking with the Azure SDK for .NET
- Azure SDK client lifetime and thread safety
- Blob Storage error codes
- Service Bus duplicate detection
- .NET Azure SDK design guidelines
Microsoft.Extensions.Azurepackage- NSubstitute documentation
Related articles

- 12 min read
Managed Identity in .NET: Stop Using Connection Strings
A credential-bearing connection string makes the first Azure request easy and every later security task harder. The same account key or …

- 13 min read
Output Caching in ASP.NET Core: What Gets Cached?
ASP.NET Core output caching does not cache an endpoint result, an EF Core query or a domain object. It caches a completed HTTP response: …

- 16 min read
Production Rate Limiting in ASP.NET Core
Most ASP.NET Core rate-limiting examples stop after registering a fixed window. That is enough to demonstrate the middleware, but it is not …
Let's Work Together
Looking for an experienced Platform Architect or Engineer for your next project? Whether it's cloud migration, platform modernization or building new solutions from scratch - I'm here to help you succeed.
