Unit Testing 101: Write your first unit test in C# with MSTest

Do you want to start writing unit tests and you don’t know how to start? Were you asked to write some unit tests on a past interview? Let’s see what a unit test is and how to write your first unit tests in C#.

1. What is a Unit test?

The book The Art of Unit Testing defines a unit test as “an automated piece of code that invokes a unit of work in the system and then checks a single assumption about the behavior of that unit of work.”

From the previous definition, a unit of work is any logic exposed through public methods. Often, a unit of work returns a value, changes the internals of the system, or makes an external invocation.

If that definition answers how to test public methods, we might ask: “What about private methods?” Short answer: we don’t test private methods. We test them when we call our code through its public methods.

In short, a unit test is code that invokes some code under test and verifies a given behavior of that code.

2. Why should we write unit tests?

Have you ever needed to change your code, but you were concerned about breaking something? I’ve been there too.

The main reason to write unit tests is to gain confidence. Unit tests allow us to make changes, with confidence that they will work. Unit tests allow change.

Unit tests work like a “safety net” to prevent us from breaking things when we add features or change our codebase.

In addition, unit tests work like living documentation. The first end-user of our code is our unit tests. If we want to know what a library does, we should check its unit tests. Often, we will find non-documented features in the tests.

I’ve included an expanded version of this post and more lessons in my book Start Testing. A step-by-step guide to writing your first C# unit tests with confidence.

Someone driving a car with his seat-belt on
Your unit tests work like a safety net. Photo by Farzanah Rosli on Unsplash

3. What makes a good unit test?

Now, we know what a unit test is and why we should write them. The next question we need to answer is: “What makes a test a good unit test?” Let’s see what all good unit tests have in common.

Our tests should run quickly

The longer our tests take to run, the less frequently we run them. And, if we don’t run our tests often, we have doors opened to bugs.

Our tests should run in any order

Tests shouldn’t depend on the output of previous tests to run. A test should create its own state and not rely upon the state of other tests.

Our tests should be deterministic

No matter how many times we run our tests, they should either fail or pass every time. We don’t want our test to use random input, for example.

Our tests should validate themselves

We shouldn’t debug our tests to make sure they passed or failed. Each test should determine the success or failure of the tested behavior. Let’s imagine we have hundreds of tests, and to make sure they pass, we have to debug every one of them. What’s the point, then?

“It could be considered unprofessional to write code without tests” - Robert Martin, The Clean Coder

4. Let’s write our first unit test with MSTest

Let’s write some unit tests for Stringie, a (fictional) library to manipulate strings with more readable methods.

One of Stringie methods is Remove(). It removes chunks of text from a string. For example, Remove() receives a substring to remove. Otherwise, it returns an empty string if we don’t pass any parameters.

"Hello, world!".Remove("Hello");
// ", world!"

"Hello, world!".Remove();
// ""

Here’s the implementation of the Remove() method for the scenario without parameters.

namespace Stringie
{
    public static class RemoveExtensions
    {
        public static RemoveString Remove(this string source)
        {
            return new RemoveString(source);
        }
    }

    public class RemoveString
    {
        private readonly string _source;

        internal RemoveString(string source)
        {
            _source = source;
        }

        public static implicit operator string(RemoveString removeString)
        {
            return removeString.ToString();
        }

        public override string ToString()
        {
            return _source != null ? string.Empty : null;
        }
    }
}

Let’s write some tests for the Remove() method. We can write a Console program to test these two scenarios.

using Stringie;
using System;

namespace TestProject
{
    class Program
    {
        static void Main(string[] args)
        {
            var helloRemoved = "Hello, world!".Remove("Hello");
            if (helloRemoved == ", world!")
            {
                Console.WriteLine("Remove Hello OK");
            }
            else
            {
                Console.WriteLine($"Remove Hello failed. Expected: ', world!'. But it was: '{helloRemoved}'");
            }

            var empty = "Hello, world!".Remove();
            if (string.IsNullOrEmpty(empty))
            {
                Console.WriteLine("Remove: OK");
            }
            else
            {
                Console.WriteLine($"Remove failed. Expected: ''. But it was: {empty}");
            }

            Console.ReadKey();
        }
    }
}

However, these aren’t real unit tests. They run quickly, but they don’t run in any order and they don’t validate themselves.

Where should we put our tests?

If you’re wondering if our tests are compiled into our Release code, we don’t ship our tests to our end users in our Release code. Tests live on different projects, separated from our production code.

Let’s create a new project for our tests.

Let’s add to the solution containing Stringie a new project of type “MSTest Test Project (.NET Core)”. Since we’re adding tests for the Stringie project, let’s name our new test project Stringie.UnitTests.

It’s my recommendation to put our unit tests in a test project named after the project they test. We can add the suffix “Tests” or “UnitTests”. For example, if we have a library called MyLibrary, we should name our test project: MyLibrary.UnitTests.

In our new test project, let’s add a reference to the Stringie project.

Visual Studio 'Solution Explorer' showing a new file 'UnitTest1.cs'
Visual Studio Solution Explorer with our new test project

After adding the new test project, Visual Studio created a file UnitTest1.cs. Let’s rename it! We are adding tests for the Remove() method, let’s name this file: RemoveTests.cs.

One way of making our tests easy to find and group is to separate them in files named after the unit of work or entry point of the code we’re testing. Let’s add the suffix “Tests”. For a class MyClass, let’s name our file: MyClassTests.

MSTest

Now, let’s see what’s inside our RemoveTests.cs file.

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Stringie.UnitTests
{
    [TestClass]
    public class RemoveTests
    {
        [TestMethod]
        public void TestMethod1()
        {
        }
    }
}

It contains one normal class and method. However, they’re annotated with two unusual attributes: [TestClass] and [TestMethod]. These attributes tell Visual Studio that our file contains unit tests to run.

The TestClass and TestMethod attributes belong to a project called MSTest. Microsoft Test Framework (MSTest) is an open-source unit testing framework. MSTest comes installed with Visual Studio.

Unit testing frameworks help us to write and run unit tests. Also, they create reports with the results of our tests. Other common unit testing frameworks include NUnit and XUnit.

How should we name our tests?

Let’s replace the name TestMethod1 with a name that follows a naming convention.

We should use naming conventions to show the feature tested and the purpose behind of our tests. Test names should tell what they’re testing.

A name like TestMethod1 doesn’t say anything about the code under test and the expected result.

ItShould

One naming convention for our test names uses a sentence to tell what they’re testing. Often, these names start with the prefix “ItShould” followed by an action. For our Remove() method, it could be:

  • ItShouldRemoveASubstring
  • ItShouldReturnEmpty
Markers and labels
Test names should tell what they're testing. Photo by Jon Tyson on Unsplash

UnitOfWork_Scenario_ExpectedResult

Another convention uses underscores to separate the unit of work, the test scenario, and the expected behavior in our test names. If we follow this convention for our example tests, we name our tests:

  • Remove_ASubstring_RemovesThatSubstring
  • Remove_NoParameters_ReturnsEmpty

With this convention, we can read our test names out loud like this: “When calling Remove with a substring, then it removes that substring.”

Following the second naming convention, our tests look like this:

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Stringie.UnitTests
{
    [TestClass]
    public class RemoveTests
    {
        [TestMethod]
        public void Remove_ASubstring_RemovesThatSubstring()
        {
        }

        [TestMethod]
        public void Remove_NoParameters_ReturnsEmpty()
        {
        }
    }
}

These names could look funny at first glance. We should use compact names in our code. However, when writing unit tests, readability is important. Every test should state the scenario under test and the expected result. We shouldn’t worry about long test names.

How should we write our tests? The AAA Principle

Now, let’s write the body of our tests.

To write our tests, let’s follow the Arrange/Act/Assert (AAA) principle. Each test should contain these three parts.

In the Arrange part, we create input values to call the entry point of the code under test.

In the Act part, we call the entry point to trigger the logic being tested.

In the Assert part, we verify the expected behavior of the code under test.

Let’s use the AAA principle to replace one of our examples with a real test. Also, let’s use line breaks to visually separate the AAA parts.

using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Stringie.UnitTests
{
    [TestClass]
    public class RemoveTests
    {
        [TestMethod]
        public void Remove_NoParameters_ReturnsEmpty()
        {
            string str = "Hello, world!";

            string transformed = str.Remove();

            Assert.AreEqual(0, transformed.Length);
        }
    }
}

We used the Assert class from MSTest to write the Assert part of our test. This class contains methods like AreEqual(), IsTrue() and IsNull().

The AreEqual() method checks if the result from a test is equal to an expected value. In our test, we used it to verify the length of the transformed string. We expect it to be zero.

Don’t repeat logic in the assertions

Let’s use a known value in the Assert part instead of repeating the logic under test in the assertions. It’s OK to hardcode some expected values in our tests. We shouldn’t repeat the logic under test in our assertions. For example, we can use well-named constants for our expected values.

Here’s an example of how not to write the Assertion part of our second test.

[TestMethod]
public void Remove_ASubstring_RemovesThatSubstring()
{
    string str = "Hello, world!";

    string transformed = str.Remove("Hello");

    var position = str.IndexOf("Hello");
    var expected = str.Substring(position + 5);
    Assert.AreEqual(expected, transformed);
}

Notice how it uses the Substring() method in the Assert part to find the string without the Hello substring. A better alternative is to use the expected result in the AreEqual() method.

Let’s rewrite our last test to use an expected value instead of repeating the logic being tested.

[TestMethod]
public void Remove_ASubstring_RemovesThatSubstring()
{
    string str = "Hello, world!";

    string transformed = str.Remove("Hello");

    // Here we use the expected result ", world!"
    Assert.AreEqual(", world!", transformed)
}

Repeating the logic under test is only one of the most common mistakes when writing unit tests.

5. How can we run a test inside Visual Studio?

To run a test, let’s right-click on the [TestMethod] attribute of the test and use “Run Test(s)”. Visual Studio will compile your solution and run the test you clicked on.

After the test runs, let’s go to the “Test Explorer” menu. There we will find the list of tests. A passed test has a green icon. If we don’t have the “Test Explorer”, we can use the “View” menu in Visual Studio and click “Test Explorer” to display it.

Visual Studio 'Test Explorer' showing a passing test
Test Explorer with our first passing test

That’s a passing test! Hurray!

If the result of a test isn’t what was expected, the Assertion methods will throw an AssertFailedException. This exception or any other unexpected exception flags a test as failed.

6. MSTest Cheatsheet

These are some of the most common Assertion methods in MSTest.

Method Function
Assert.AreEqual Check if the expected value is equal to the found value
Assert.AreNotEqual Check if the expected value isn’t equal to the found value
Assert.IsTrue Check if the found value is true
Assert.IsFalse Check if the found value is false
Assert.IsNull Check if the found value is null
Assert.IsNotNull Check if the found value isn’t null
Assert.ThrowsException Check if a method throws an exception
Assert.ThrowsExceptionAsync Check if an async method throws an exception
StringAssert.Contains Check if a found string contains a substring
StringAssert.Matches Check if a found string matches a regular expression
StringAssert.DoesNotMatch Check if a found string doesn’t match a regular expression
CollectionAssert.AreEquivalent Check if two collections contain the same elements
CollectionAssert.AreNotEquivalent Check if two collections don’t contain the same elements
CollectionAssert.Contains Check if a collection contains an element
CollectionAssert.DoesNotContain Check if a collection doesn’t contain an element

7. Conclusion

Voilà! That’s how you write your first unit tests in C# with MSTest. Don’t forget to follow naming conventions and use the Assert class when writing unit tests.

If you want to practice writing more tests for Stringie, check my Unit Testing 101 repository on GitHub.

canro91/Testing101 - GitHub

In this repo, you will find two lessons: one to write some unit tests and another to fix some unit tests.

For more content about unit testing, don’t miss the entire series Unit Testing 101.

This post was originally published on exceptionnotfound.net as part of the Guest Writer Program. I’d like to thank Matthew for helping me to edit this post.

How not to write Dynamic SQL

Last time, I showed you three tips to debug your Dynamic SQL. Let’s take a step back. Let’s see what is a dynamic SQL query and how to use one to rewrite a stored procedure with optional parameters.

Dynamic SQL is a string with a query to execute. In a stored procedure with optional parameters, Dynamic SQL is used to build a string containing a query with only the comparisons and clauses for the parameters passed with a non-default value.

Without Dynamic SQL

Let’s go back to the stored procedure dbo.usp_SearchUsers from our previous post on debugging Dynamic SQL queries. This stored procedure finds StackOverflow users by display name or location or both.

Without Dynamic SQL, we end up with funny comparisons in the WHERE clause. First, we check if the optional parameters have value. To then, with an OR, add the right comparisons. Everything in a single statement.

CREATE OR ALTER PROC dbo.usp_SearchUsers
  @SearchDisplayName NVARCHAR(100) = NULL,
  @SearchLocation NVARCHAR(100) = NULL
AS
BEGIN
    
  SELECT TOP 100 *
  FROM dbo.Users u
  WHERE (@SearchDisplayName IS NULL OR DisplayName LIKE @SearchDisplayName)
    AND (@SearchLocation IS NULL OR Location LIKE @SearchLocation);
END
GO

Let’s run our stored procedure searching only by DisplayName and see its execution plan.

Execution plan of searching users by DisplayName
Search for only a single user by DisplayName

Notice SQL Server had to scan the DisplayName index and see the number of rows read.

Sometimes, we use the ISNULL() or COALESCE() functions instead of IS NULL. But, those are variations on the same theme.

The more optional parameters our stored procedure has, the worse our query gets. SQL Server will scan entire tables or indexes to satify our query.

How not to write Dynamic SQL
Photo by Nadine Shaabana on Unsplash

With Dynamic SQL, the wrong way

Probably, we hear about Dynamic SQL somewhere on the Internet and we decide to use it.

Then, we write the next version of our stored procedure. Something like the one below.

CREATE OR ALTER PROC dbo.usp_SearchUsersWithWrongDynamicSQL
  @SearchDisplayName NVARCHAR(100) = NULL,
  @SearchLocation NVARCHAR(100) = NULL
AS
BEGIN
 
  DECLARE @StringToExecute NVARCHAR(4000);
    
  SET @StringToExecute = N'SELECT TOP 100 *
  FROM dbo.Users u
  WHERE (@SearchDisplayName IS NULL OR DisplayName LIKE @SearchDisplayName)
    AND (@SearchLocation IS NULL OR Location LIKE @SearchLocation);';

  EXEC sp_executesql @StringToExecute, 
    N'@SearchDisplayName NVARCHAR(100), @SearchLocation NVARCHAR(100)', 
    @SearchDisplayName, @SearchLocation;
END
GO

We moved the exact same query to a string and asked SQL Server to execute that string. That won’t make any difference between the execution plans of both versions. We only put makeup on the problem. Arggg!

With Dynamic SQL, the right way

With Dynamic SQL, we want to create smaller queries for the different set of parameters passed to our stored procedure.

We need to add only the comparisons and clauses for the parameters passed with non-default values.

Let’s rewrite the stored procedure to include the conditions to the WHERE based on the parameters passed.

CREATE OR ALTER PROC dbo.usp_SearchUsers_DynamicSQL
  @SearchDisplayName NVARCHAR(100) = NULL,
  @SearchLocation NVARCHAR(100) = NULL
AS
BEGIN
 
  DECLARE @StringToExecute NVARCHAR(4000);
    
  SET @StringToExecute = N'SELECT TOP 100 *
  FROM dbo.Users u
  WHERE 1 = 1';

  IF @SearchDisplayName IS NOT NULL
    SET @StringToExecute = @StringToExecute + N' AND DisplayName LIKE @SearchDisplayName ';

  IF @SearchLocation IS NOT NULL
    SET @StringToExecute = @StringToExecute + N' AND Location LIKE @SearchLocation ';

  EXEC sp_executesql @StringToExecute, 
    N'@SearchDisplayName NVARCHAR(100), @SearchLocation NVARCHAR(100)', 
    @SearchDisplayName, @SearchLocation;
END
GO

First, we created a @StringToExecute variable with the first part of the SELECT. We added 1 = 1 on the WHERE to easily add conditions in the next steps.

Instead of, 1 = 1 we can also use a common or required condition for all other set of parameters.

Then, notice the two IF statements. We added the conditions to the WHERE clause depending on the parameter passed.

After that, we executed the query inside the string with sp_executesql with the parameter declaration and the parameters themselves.

Execution plan of searching users by DisplayName
Search for only a single user by DisplayName with Dynamic SQL

With Dynamic SQL, our stored procedure will generate one execution plan for each set of different parameters. That’s the point of using Dynamic SQL.

This time, SQL Server could seek on DisplayName instead of scanning it. That’s better.

Voilà! That’s how NOT to write a stored procedure with optional parameters with Dynamic SQL. Notice that to make things simple, we didn’t follow all the tips to make our Dynamic SQL easier to debug.

If you’re interested in more content about SQL and SQL Server, check my posts on Six SQL Server performance tuning tips and How to format your SQL queries.

Happy coding!

TIL: How to convert 2-digit year to 4-digit year in C#

Today I was working with credit cards and I needed to convert a 2-digit year to a 4-digit one in C#. The first thing that came to my mind was adding 2000 to it. But it didn’t feel right. It wouldn’t be a problem in hundreds of years, though.

To convert 2-digit year into a 4-digit year, use the ToFourDigitYear method inside your current culture’s calendar.

CultureInfo.CurrentCulture.Calendar.ToFourDigitYear(21)
// 2021

But, if you’re working with a string containing a date, create a custom CultureInfo instance and set the maximum year to 2099. After that, parse the string holding the date with the custom culture. Et voilà!

CultureInfo culture = new CultureInfo("en-US");
culture.Calendar.TwoDigitYearMax = 2099;

string dateString = "1 Jan 21";
DateTime.TryParse(dateString, culture, DateTimeStyles.None, out var result);
// true, 1/1/2021 12:00:00 AM

Sources: Convert a two digit year, Parse string dates with two digit year

Visual Studio snippets for Moq

These days, I use Moq a lot. There are things I like and I don’t like about creating fakes with Moq. But it’s simple and easy to use.

I use the same four Moq methods all the time. Setup, ReturnAsync, ThrowsAsync and Verify. That’s all you need. I decided to create snippets inside Visual Studio to avoid typing the same method names every time. These are the snippets I use.

Create a Mock with Moq

Use mn to create a Mock. It expands to var mock = new Mock<>();.

mn to create a Mock
Use mn to create a Mock

Setup and Return

With a mock instance, use mr to Setup a method to Return something.

mr to Setup/Return
Use mr to Setup/Return

Setup and ThrowsException

If you want to throw an exception from your mock, use mt.

mt to Setup/ThrowsException
Use mt to Setup/ThrowsException

Also, you can use mra and mta for the asynchronous version of Return and ThrowsException respectively.

If you want to use the same snippets I use, download the snippets file from VSMoqSnippets repository.

To load snippets into Visual Studio, from the “Tools” menu, choose “Code Snippets Manager” and import the snippets file.

canro91/VSMoqSnippets - GitHub

Voilà! Those are the snippets I use for Moq. Check my Visual Studio setup for more settings and extensions. Do you want to learn more about fakes? Read what are fakes in unit testing and these tips for better stubs and mocks.

Happy coding!

Decorator pattern. A real example in C#

I’ve been working with Stripe to take payments. Depending on the volume of requests you make to the Stripe API, you might exceed the maximum number of requests per second. This is how we can implement a retry mechanism using the Decorator pattern in C#.

A Decorator wraps another object to extend its responsabilities, without modifying its existing behavior, while keeping the same signature of public methods. Decorators are used to add orthogonal responsibilities like logging, caching and retrying.

Let’s use Marvel movies to understand the Decorator pattern. When IronMan wore the HULKBUSTER suit in the Age of Ultron, he implemented the Decorator pattern. He had a new functionality, stopping the Hulk, while keeping his same functions, being IronMan. I hope you got it!

Decorator pattern. A real example in C#
When you wear a jacket, you use the Decorator pattern too. Photo by Archie on Unsplash

Naive Retry logic

Let’s start with a PaymentService. This service collects everything it needs to start a payment with Stripe. For example, customer id, fees, destination account, etc. Then, it uses a PaymentIntentService to call Stripe API using its C# client.

This would be the CreatePaymentIntentAsync() method inside the PaymentService.

public class PaymentService : IPaymentService
{
    private readonly IPaymentIntentService _paymentIntentService;
    private readonly IFeeService _feeService;

    public PaymentService(IPaymentIntentService paymentIntentService, IFeeService feeService)
    {
        _paymentIntentService = paymentIntentService;
        _feeService_ = feeService;
    }

    public async Task<PaymentIntentDetails> CreatePaymentIntentAsync(
        PaymentRequestViewModel request,
        IDictionary<string, string> metadata)
    {
        var currencyCode = request.CurrencyCode;
        var description = request.Description;
        var amountInUnits = request.Amount.ToMainUnits();
        var gatewayAccountId = request.GatewayAccountId;

        var applicationFee = _feeService.GetApplicationFee(request);
        metadata.AddFees(applicationFee);

        var paymentIntentOptions = new PaymentIntentCreateOptions
        {
            Amount = amountInUnits,
            Currency = currencyCode,
            ApplicationFeeAmount = applicationFee,
            Description = description,
            Metadata = metadata,
            Confirm = true,
            CaptureMethod = "manual",
            OnBehalfOf = gatewayAccountId,
            TransferData = new PaymentIntentTransferDataOptions
            {
                Destination = gatewayAccountId
            }
        };

        try
        {
            var paymentIntent = await _paymentIntentService.CreateAsync(paymentIntentOptions, GetRequestOptions());

            return GetSuccessfulPaymentIntentDetails(request, paymentIntent);
        }
        catch (StripeException stripeException)
        {
            return GetFailedPaymentIntentDetails(request, stripeException);
        }
    }
}

We want to retry the method CreateAsync() if it reaches the maximum number of allowed requests by Stripe at a given time.

We can add retry logic using a helper method. And, wrap the call to the CreateAsync() method inside the helper method. Something like this,

try
{
    var paymentIntent = await RetryAsync(async () =>
    {
        return await _paymentIntentService.CreateAsync(paymentIntentOptions, GetRequestOptions());
    });

    return GetSuccessfulPaymentIntentDetails(paymentRequest, paymentIntent);
}
catch (StripeException stripeException)
{
    return GetFailedPaymentIntentDetails(paymentRequest, stripeException);
}

The RetryAsync() helper method will execute the API call a fixed number of times if it fails with a TooManyRequests status code. If it fails with a different exception or status code, it propagates the exception to the caller.

This is a simple implementation of a retry method.

protected async Task<TResult> RetryAsync<TResult>(Func<Task<TResult>> apiCommand, int maxRetryCount = 3)
{
    var exceptions = new List<Exception>();
    var retryCount = 0;

    while (true)
    {
        try
        {
            return await apiCommand();
        }
        catch (StripeException ex) when (ex.HttpStatusCode == HttpStatusCode.TooManyRequests)
        {
            exceptions.Add(ex);

            if (retryCount == retryCountMax)
            {
                throw new AggregateException("Too many requests", exceptions);
            }

            retryCount++;
        }
    }
}

Later, we can replace this helper method with a more robust implementation using Polly, for example. It can include incremental delays between failed attempts and timeouts.

But, using this helper method implies wrapping the methods to retry inside our helper method all over our codebase. Hopefully, if we have a singe place to take payments, that wouldn’t be a problem. Also, our PaymentService mixes business logic with retry logic. That’s smelly. We should keep responsabilities separated.

Retry logic with Decorator pattern: Let’s Decorate

For a more clean solution, let’s use the Decorator pattern.

First, let’s create a decorator called RetryablePaymentIntentService for the PaymentIntentService. Since we want to keep the same API of public methods, the decorator should inherit from the same interface, IPaymentIntentService.

public class RetryablePaymentIntentService : IPaymentIntentService
{
    public Task<PaymentIntent> CreateAsync(PaymentIntentCreateOptions options, RequestOptions requestOptions = null, CancellationToken cancellationToken = default)
    {
        // We will fill the details in the next steps
    }
}

The decorator will only handle the retry logic. It will use the existing PaymentIntentService to call Stripe. The decorator will receive another IPaymentIntentService in its constructor.

public class RetryablePaymentIntentService : IPaymentIntentService
{
    private readonly IPaymentIntentService _decorated;

    public RetryablePaymentIntentService(IPaymentIntentService decorated)
    {
        _decorated = decorated;
    }

    public Task<PaymentIntent> CreateAsync(PaymentIntentCreateOptions options, RequestOptions requestOptions = null, CancellationToken cancellationToken = default)
    {
        // We will fill the details in the next steps
    }
}

Notice, we named the field in the decorator, _decorated. And, yes, the decorator inherits and receives the same type. That’s the trick!

Next, we need to fill in the details. To complete our decorator, let’s use our previous RetryAsync() method. Our decorator will look like this,

public class RetryablePaymentIntentService : PaymentIntentService
{
    private readonly PaymentIntentService _decorated;

    public RetryablePaymentIntentService(PaymentIntentService decorated)
    {
        _decorated = decorated;
    }

    public Task<PaymentIntent> CreateAsync(PaymentIntentCreateOptions options, RequestOptions requestOptions = null, CancellationToken cancellationToken = default)
    {
        return RetryAsync(async () =>
        {
            return await _decorated.CreateAsync(paymentIntentOptions, requestOptions, cancellationToken);
        });
    }
    
    // Same RetryAsync method as before...
}

Now, our decorator is ready to use it. In the PaymentService, we can replace the simple PaymentIntentService by our new RetryablePaymentIntentService. Both services implement the same interface.

We can create our decorator like this,

new RetryablePaymentIntentService(new PaymentIntentService(/* Other dependencies */));

Inject Decorators into ASP.NET Core container

Let’s register our decorator

But, if you’re using an ASP.NET Core API project, we can use the dependency container to build the decorator.

Let’s use an extension method AddPaymentServices() to group the registration of our services. You can register your services directly into the Startup class. No problem!

public static class ServiceCollectionExtensions
{
    public static void AddPaymentServices(this IServiceCollection services)
    {
        services.AddTransient<PaymentIntentService>();
        services.AddTransient<IPaymentIntentService>((provider) =>
        {
          var decorated = provider.GetRequiredService<PaymentIntentService>();
          return new RetryablePaymentIntentService(decorated);
        });
        services.AddTransient<IPaymentService, PaymentService>();
    }
}

This time, we registered the original PaymentIntentService without specifying an interface. We only used the IPaymentIntentService to register the decorator. When resolved, the PaymentService will receive the decorator instead of the original service without retry logic.

Let’s use Scrutor to register our decorator

Optionally, we can use Scrutor to register the decorated version of the IPaymentIntentService. Scrutor is a library that adds more features to the built-in dependencies container. Don’t forget to install the Scrutor NuGet package into your project, if you choose this route.

In that case, our AddPaymentServices() will look like this,

public static class ServiceCollectionExtensions
{
    public static void AddPaymentServices(this IServiceCollection services)
    {
        services.AddTransient<IPaymentIntentService, PaymentIntentService>();
        // With Scrutor, we need the method Decorate
        services.Decorate<IPaymentIntentService, RetryablePaymentIntentService>();
        services.AddTransient<IPaymentService, PaymentService>();
    }
}

Notice, this time we have explicitly register two entries for the IPaymentIntentService. The Decorate() method does the trick for us.

Voilà! That’s how we can implement the Decorator pattern to retry API calls. We can also use the decorator pattern to bring logging or caching to our services. Check how you can use the Decorator pattern to add a Redis caching layer with ASP.NET Core.

For more real-world examples, check my post on Primitive Obsession. That’s about handling Stripe currency units. If you want my take on another pattern, check my post about the Pipeline pattern.

Happy coding!