What you'll learn

When a NuGet advisory affects a package in your dependency graph, you need to assess the affected version, identify a supported fix, and verify that the update preserves required behavior.

If domain services depend directly on package-specific types, a replacement can touch many call sites and business rules at once. An application-owned interface and adapter provide a seam for changing the implementation while keeping later package-specific changes out of domain code.

This article compares three strategies for a problematic NuGet dependency: Wrap, Replace, and Rewrite. You will see how to isolate a package behind an interface, select a replacement, or remove the dependency when owning the behavior is practical. The examples distinguish architectural isolation from security remediation.

Why it matters

When a NuGet Package Leaks Into Your Domain, Every Change Becomes Risky

Consider an order-processing service where a ShippingCalculator type from a third-party package is injected directly into the domain service:

C#


// ❌ The NuGet type leaks directly into your domain
using LegacyShippingLib; // the vulnerable package

public class OrderService
{
    private readonly ShippingCalculator _calculator; // NuGet type in domain

    public OrderService(ShippingCalculator calculator)
    {
        _calculator = calculator;
    }

    public decimal GetShippingCost(Order order)
        => _calculator.Calculate(order.WeightKg, order.DestinationPostcode);
}
            

To replace LegacyShippingLib, this service and every other direct consumer must change.

Isolation Does Not Remediate a Vulnerability

An adapter does not remove or fix a vulnerable package. Continue remediation according to the advisory, your exposure assessment, and your organization's response policy while you prepare the replacement. Do not treat isolation as evidence that the finding is resolved.

A package can also need replacement because it is unmaintained, incompatible, or unsuitable for licensing or product requirements. Those concerns call for their own review; they are not equivalent to a confirmed vulnerability.

Three Strategies for a Dependency Change

The strategies describe different implementation choices. Choose based on remediation needs, compatibility, maintenance, licensing, and the cost of owning the behavior—not severity alone:

  • Wrap — Put an application-owned interface and adapter around the existing dependency. This reduces coupling and creates a replacement seam, but leaves the package and any vulnerability in the dependency graph. Use it as a refactoring step, not as a vulnerability fix.
  • Replace — Implement the interface with a supported alternative and remove the old package reference where no longer needed. Update dependency-injection registration and verify the resulting graph and behavior.
  • Rewrite — Own a small, well-specified behavior when its maintenance, correctness, and support costs are acceptable. Reimplementing complex or regulated behavior can increase risk rather than reduce it.

These are options, not mandatory stages. A direct update may be simpler than adding an abstraction. If you introduce a seam first, the initial refactoring still changes consumers; later implementations can change without revisiting those consumers, provided the interface continues to express the required behavior.

Implementation

The Scenario: A Vulnerable Shipping Cost Calculator

In this example, three services consume a shipping package directly. The refactoring moves those consumers to an application-owned interface, then lets an adapter translate to each package API. A real advisory still requires a separate, verified remediation.

Step 1 — Wrap: Define the Abstraction and Create an Adapter

Define an IShippingCostCalculator interface in an application abstractions project. Keep package-specific types out of its signatures:

C#


// Project: OrderManagement.Application.Abstractions
// No NuGet references — pure domain contract

namespace OrderManagement.Application.Abstractions;

public interface IShippingCostCalculator
{
    decimal Calculate(decimal weightKg, string destinationPostcode);
}
            

Create an adapter that implements the interface and translates the external API. Restrict package references to the infrastructure that needs them, and enforce that dependency rule with your project structure and architecture checks:

C#


// Project: OrderManagement.Infrastructure.Shipping.Legacy
// Only project with a <PackageReference> to LegacyShippingLib

using LegacyShippingLib;
using OrderManagement.Application.Abstractions;

namespace OrderManagement.Infrastructure.Shipping.Legacy;

// The adapter instantiates the third-party type internally.
// Nothing outside this project ever sees ShippingCalculator.
public sealed class LegacyShippingAdapter : IShippingCostCalculator
{
    private readonly ShippingCalculator _legacyCalculator = new();

    public decimal Calculate(decimal weightKg, string destinationPostcode)
        => _legacyCalculator.Calculate(weightKg, destinationPostcode);
}
            

Update every service that previously referenced ShippingCalculator directly to inject IShippingCostCalculator instead. The initial refactoring updates existing consumers; later package API changes can remain in the adapter while the application contract stays suitable:

C#


// ✅ Domain code now depends only on the abstraction
using OrderManagement.Application.Abstractions;

public class OrderService
{
    private readonly IShippingCostCalculator _shippingCalculator;

    public OrderService(IShippingCostCalculator shippingCalculator)
    {
        _shippingCalculator = shippingCalculator;
    }

    public decimal GetShippingCost(Order order)
        => _shippingCalculator.Calculate(order.WeightKg, order.DestinationPostcode);
}
            

Register the adapter in your DI container:

C#


// Program.cs — Wrap: register the legacy adapter
builder.Services.AddScoped<IShippingCostCalculator, LegacyShippingAdapter>();
            

This step reduces coupling; it does not remediate an advisory. Continue with the package update or replacement promptly under your response policy. The initial refactoring also requires updating each existing consumer to use the interface.

Step 2 — Replace: Swap in a Safer Package

With consumers depending on the interface, add an adapter for the supported replacement package. The package APIs here are illustrative; this replacement accepts a double weight, so validate units, precision, and rounding against the real provider's API before using a conversion like this:

C#


// Project: OrderManagement.Infrastructure.Shipping.Modern
// Only project with a <PackageReference> to ModernShippingLib

using ModernShippingLib;
using OrderManagement.Application.Abstractions;

namespace OrderManagement.Infrastructure.Shipping.Modern;

// The adapter instantiates the third-party type internally.
// Illustrative API conversion only: verify precision and rounding requirements.
public sealed class ModernShippingAdapter : IShippingCostCalculator
{
    private readonly ShipmentRateEngine _rateEngine = new();

    public decimal Calculate(decimal weightKg, string destinationPostcode)
        => _rateEngine.ComputeRate(destinationPostcode, (double)weightKg);
}
            

Select the new implementation in the composition root. The exact changes depend on how your adapters and projects are registered:

C#


// Program.cs — Replace: swap to the safe adapter (one-line change)
// Before: builder.Services.AddScoped<IShippingCostCalculator, LegacyShippingAdapter>();
builder.Services.AddScoped<IShippingCostCalculator, ModernShippingAdapter>();
            

Before switching, capture representative, privacy-safe outputs from the old implementation and run regression tests against both adapters. Passing tests show that the tested cases match; they do not prove equivalence for every possible input or establish that the old behavior was correct.

Step 3 — Rewrite: Remove the External Dependency Entirely

If the behavior is small, well specified, and practical for your team to maintain, you can implement it without the external package. This simplified example is illustrative only; shipping prices and postcode rules need product-specific validation: IShippingCostCalculator using only built-in .NET types:

C#


// Project: OrderManagement.Application.Shipping
// No NuGet references — pure .NET implementation

using OrderManagement.Application.Abstractions;

namespace OrderManagement.Application.Shipping;

public sealed class FlatRateShippingCalculator : IShippingCostCalculator
{
    private const decimal BaseRatePounds = 3.99m;
    private const decimal RatePerKgPounds = 1.25m;

    // Extend with additional postcode areas and zone surcharges as needed
    private static readonly Dictionary<string, decimal> ZoneSurcharges =
        new(StringComparer.OrdinalIgnoreCase)
        {
            ["BT"] = 5.00m,  // Northern Ireland
            ["GY"] = 7.50m,  // Guernsey
            ["JE"] = 7.50m,  // Jersey
        };

    public decimal Calculate(decimal weightKg, string destinationPostcode)
    {
        var areaCode = destinationPostcode.Length >= 2
            ? destinationPostcode[..2].Trim()
            : destinationPostcode;

        var surcharge = ZoneSurcharges.GetValueOrDefault(areaCode, defaultValue: 0m);

        return BaseRatePounds + (weightKg * RatePerKgPounds) + surcharge;
    }
}
            

Register it with one line — the same pattern as before:

C#


// Program.cs — Rewrite: no external NuGet package needed
builder.Services.AddScoped<IShippingCostCalculator, FlatRateShippingCalculator>();
            

Remove the old PackageReference only after checking that no other project or package still requires it. Confirm the resolved graph and rerun audit and regression tests before closing the finding.

How the Three Strategies Relate

When these strategies share an application-owned contract, the domain services can depend on IShippingCostCalculator while the implementation behind it can vary:

Text


┌──────────────────────────────────────────────────────────────────┐
│  Domain Code                                                     │
│  OrderService, QuoteService, CheckoutService                     │
│  depend on: IShippingCostCalculator                              │
│  know nothing about: LegacyShippingLib                           │
└────────────────────┬─────────────────────────────────────────────┘
                     │ IShippingCostCalculator
          ┌──────────▼────────────────────────────────┐
          │  DI Container — one registration per env  │
          └──────────┬────────────────────────────────┘
                     │
        ┌────────────┼───────────────────┐
        │            │                   │
  ┌─────▼──────┐ ┌───▼────────────┐ ┌───▼──────────────────────┐
  │  Wrap      │ │  Replace       │ │  Rewrite                 │
  │  Legacy    │ │  Modern        │ │  FlatRate                │
  │  Adapter   │ │  Adapter       │ │  Calculator              │
  │ (old pkg)  │ │ (new package)  │ │  (zero NuGet deps)       │
  └────────────┘ └────────────────┘ └──────────────────────────┘
            

The abstraction can keep later implementation changes out of the services, but project references, adapter code, registrations, and tests may also need updates. Keep the focus on removing the affected package and validating the replacement.

Quick Reference: When to Apply Each Strategy

Text


Strategy  | Best Applied When                               | Important Limit
----------|-------------------------------------------------|-----------------------------
Wrap      | Consumers are coupled to a package API          | Does not fix an advisory
          | A seam is needed before changing implementations |
----------|-------------------------------------------------|-----------------------------
Replace   | A supported alternative fits the required API    | Audit graph and regression
          | Compatibility can be validated                   | tests after the change
----------|-------------------------------------------------|-----------------------------
Rewrite   | Behavior is small and well specified             | Team owns correctness and
          | Owning it costs less than keeping the dependency | ongoing maintenance
            

Summary

Choose a dependency strategy that addresses the actual finding and keeps the replacement behavior testable. An abstraction can reduce future coupling, but only a verified update or removal resolves the affected package version.

  • Direct use of package types in domain code increases the number of consumers that may need changes during a replacement.
  • Wrap: create an application-owned interface (such as IShippingCostCalculator) and an adapter project that is the package-specific implementation boundary. This reduces coupling but does not remediate a vulnerable version.
  • Replace: implement the interface with a supported package and verify dependency resolution, audit results, and regression tests.
  • Rewrite: own the implementation only when behavior is bounded, specified, and maintainable by your team.
  • Test representative old and new behavior. A passing test suite supports the cases it exercises; add explicit assertions for the intended contract and important edge cases.

To identify known advisories in the resolved package graph before choosing a remediation, read How to Find NuGet Dependency Vulnerabilities Before They Find You in .NET — it covers dotnet list package --vulnerable, NuGet Audit, and CI pipeline configuration to catch dependency risks automatically before they reach production.