DEV Community

Cover image for How To Implement The Decorator Pattern With Autofac
Dev Leader
Dev Leader

Posted on • Originally published at devleader.ca

How To Implement The Decorator Pattern With Autofac

In the realm of software development, understanding theoretical concepts is only half the battle. Practical examples serve as a bridge, translating abstract ideas into tangible implementations that can be visualized, tested, and refined. They provide a hands-on approach, allowing developers to see how a concept works in a real-world setting, making the learning process more effective and relatable. So let’s see how to implement the decorator pattern with Autofac!

The Decorator Pattern is a design pattern that allows behavior to be added to individual objects, either statically or dynamically, without affecting the behavior of other objects from the same class. It promotes the Single Responsibility Principle, ensuring that each class has only one reason to change. While the pattern itself offers a structured approach to enhance object functionalities, its implementation can become cumbersome, especially when multiple decorators are involved.

This is where Autofac comes into play. Autofac is a popular Inversion of Control container for .NET, which simplifies the process of registering and resolving dependencies, including decorators. By leveraging Autofac, developers can seamlessly implement the Decorator Pattern, ensuring that dependencies are injected appropriately and that the overall code remains clean and maintainable. In this article, we’ll delve into practical examples of how to combine the power of the Decorator Pattern with the simplicity of Autofac in different application contexts.


Autofac Example 1: Implement The Decorator Pattern In A Simple Console Application

Setting Up Autofac in a Console Application

Before we see how to implement the Decorator Pattern with Autofac, it’s essential to set up Autofac in your console application. Here’s a step-by-step guide:

  1. Start by creating a new Console Application in Visual Studio.

  2. Use the NuGet Package Manager to install the Autofac package.

  3. Once installed, you can initialize the Autofac container. This container will be responsible for registering your classes and resolving dependencies.

We’ll walk through that last step in more detail so we can see how we can use Autofac to implement the decorator pattern.

Defining Core Interfaces and Classes for the Console App

For our console application, let’s consider a scenario where we have a basic IMessageService that sends messages. We’ll then decorate this service to add additional functionalities.

public interface IMessageService
{
    void SendMessage(string message);
}

public class MessageService : IMessageService
{
    public void SendMessage(string message)
    {
        Console.WriteLine(message);
    }
}
Enter fullscreen mode Exit fullscreen mode

In this basic setup, our MessageService simply outputs a message to the console.

Crafting Decorators for the Console App

Now, let’s create a decorator to enhance our MessageService. Suppose we want to add a timestamp to each message. We can achieve this with a decorator:

public class TimestampedMessageServiceDecorator : IMessageService
{
    private readonly IMessageService _innerService;

    public TimestampedMessageServiceDecorator(IMessageService innerService)
    {
        _innerService = innerService;
    }

    public void SendMessage(string message)
    {
        var timestampedMessage = $"{DateTime.Now}: {message}";
        _innerService.SendMessage(timestampedMessage);
    }
}
Enter fullscreen mode Exit fullscreen mode

This decorator wraps around our original MessageService and adds a timestamp to the message before sending it.

Registering and Resolving Dependencies with Autofac in the Console App

With our core classes and decorators in place, we can now register them with Autofac and resolve dependencies:

var builder = new ContainerBuilder();

// Register core services
builder
    .RegisterType<MessageService>()
    .As<IMessageService>();

// Register decorators
builder.RegisterDecorator<TimestampedMessageServiceDecorator, IMessageService>();

var container = builder.Build();

// Resolve dependencies and use the service
using var scope = container.BeginLifetimeScope();
var messageService = scope.Resolve<IMessageService>();
messageService.SendMessage("Hello, Decorator Pattern!");
Enter fullscreen mode Exit fullscreen mode

When you run the application, you’ll see the message printed with a timestamp, demonstrating the decorator in action.


Autofac Example 2: Implement The Decorator Pattern in an ASP.NET Web Application

Want to see how to implement the decorator pattern in ASP.NET? Head over to my site to read the full Autofac example with source code! Otherwise, you could watch about it in this video:

If you’d like to have a summary of full articles, videos, and software engineering topics delivered right to your inbox then subscribe to my newsletter!

Top comments (0)