Blog / Design Patterns
The Proxy Design Pattern in C# and .Net
  • Dec 27, 2020
  • 62
  • 97

The last design pattern in the Structural Category is the Proxy Design Pattern. Let's take a look at the definition of this design pattern, when and how to implement this design pattern in C# and .Net.

Note: Code can be downloaded at my Github.


Advertisement
 


1. What is the Proxy Design Pattern?

The Proxy acts like a gateway or a substitute which controls the access to the other object and allows to perform actions either before or after the requests get through that object. The Proxy Design Pattern falls into the Structural Category.

In computer programming, the proxy pattern is a software design pattern. A proxy, in its most general form, is a class functioning as an interface to something else.

2. When to implement the Proxy Design Pattern?

In general, the Proxy Design Pattern is used when we need a gateway to the main object's complexity from the client. By doing so, when the object is needed, we just need to initialize the proxy to access the object.

A real-world example is a Credit Card which is a proxy for a bank account. This proxy is a gateway to your bank account to perform money transaction functionalities. A consumer feels great because there’s no need to carry loads of cash around. A shop owner is also happy since the income from a transaction gets added electronically to the shop’s bank account without the risk of losing the deposit or getting robbed on the way to the bank.

Without your credit card, you need to go to bank to get cash every time you want to buy something. The shop owner needs to do the same to deposit your money to their bank if they don't want to keep cash at home for security reasons.

3. How to implement the Proxy Design Pattern?

Take the bank transaction example above, we can implement similarly in code to see how Proxy helps your applications process the request.

Let's say you and your application are the client of a bank object. Both can access the bank to make transaction either in person or through a proxy. You are not able to modify the MakeTransaction code inside the Bank object.

Step 1: Create an Interface

1
2
3
4
public interface IBank
{
    void MakeTransaction();
}

Step 2: Create a Main class

1
2
3
4
5
6
7
8
9
10
public class Bank : IBank
{
    public void MakeTransaction()
    {
        Console.WriteLine("Bank Making Transaction:");
        Console.WriteLine("Start Transaction");
        Console.WriteLine("Making Transaction ...");
        Console.WriteLine("Bank Ending Transaction");
    }
}

Step 3: Create a Proxy

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class BankProxy : IBank
{
    private Bank _realBank;
 
    public BankProxy(Bank realBank)
    {
        this._realBank = realBank;
    }
 
    public void MakeTransaction()
    {
        if (this.CheckAccess())
        {
            this._realBank.MakeTransaction();
 
            this.LogAccess();
        }
    }
 
    public bool CheckAccess()
    {
        // Some real checks should go here.
        Console.WriteLine("Proxy: Checking access prior to firing a real request.");
 
        return true;
    }
 
    public void LogAccess()
    {
        Console.WriteLine("Proxy: Logging the time of request.");
    }
}

Step 4: Implement code in Client

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Program
{
    static void Main(string[] args)
    {
        Client client = new Client();
 
        Console.WriteLine("Making Transaction without a Proxy:");
        Console.WriteLine("A client needs to go to bank in person and make transaction.");
        Console.WriteLine("A bank representative needs to validate your access by verifying your information.");
        Bank bank = new Bank();
        client.ClientCode(bank);
        Console.WriteLine("You leave the bank in person.");
 
        Console.WriteLine();
 
        Console.WriteLine("Making Transaction with a Proxy:");
        Console.WriteLine("Client: Executing the same client code with a proxy:");
        BankProxy proxy = new BankProxy(bank);
        client.ClientCode(proxy);
    }
}
 
public class Client
{
    public void ClientCode(IBank bank)
    {
        // ...
 
        bank.MakeTransaction();
 
        // ...
    }
}

Output:


Done! You can see the difference with and without the Proxy. By using the Proxy, it's possible to handle the request before and after processing that request in the main object.

4. Conclusion

I hope this post about the last Structural Design Pattern is helpful for your applications. We will see next time to discuss the Behavioral Design Pattern. Please let me know your thoughts in the comment section below.


If you have a Website or a Web API developed by using .Net Core and looking for a way to publish your applications, this post will explain how to do it using GoDaddy Windows Hosting.Note: at this mome ...

Search text in Stored Procedure in SQL SELECT DISTINCT o.name AS Object_Name, o.type_desc FROM sys.sql_modules m INNER JOIN sys.objects o ON m.object_id = o ...

Using cherry-pick to select specific commits for your Pull Request.1. Create a new branch based on the target of the Pull Requestgit branch cherry-branch origin/master2. Switch to a new branchgit chec ...

After deployment Angular and API on IIS, it's working fine unless I refresh the page. Once refreshed, the web encountered 404 error. In this article, I will explain how to resolve this.Since Angular i ...

There are some benefits of keeping both UI and API parts in the same place for small projects. In this article, I will explain how I did to deploy Angular Web and ASP .Net Core API in the same folder ...

I got CORS error after publishing my API and Angular app to IIS even though CORS is enabled and the origins of the Angular app is added. Below is how I resolved this issue.Just simple, make sure you s ...

1. The Situation:Error Message: Pulse Secure Application failed to load Java. Please install correct JRE version.Description: This issue happens when I'm using a M1 Mac with a correct version of ...

Accelerated Mobile Pages (AMP) focuses on delivering static content from publishers as quickly as possible and possibly rewards early adopters with a boost in rank. Let's see how to implement it ...

Below is how to decrypt/convert a Hex string value into text using VB.Net:Decrypting Hex string value to string in VB.Net Function HexToString(ByVal hex As String) As String Dim text As New Sy ...