App Domain in .NET Framework

App Domain in .NET Framework

In this article, I am going to discuss App Domain in .NET Framework and in what scenarios we need them with examples. Please read our previous article where we discussed Assembly, DLL, and EXE in detail. The App Domain (Application Domain) in the .NET Framework is a logically isolated container inside which the .NET Code runs.

Understanding App Domain in .NET:

Let us understand App Domain with an example. Please create a console application and then copy and paste the following code in Program.cs class file. This is a very simple application. Here we created two classes MyClass1 and MyClass2. Then we create objects of both these classes inside the Main method of Program class and loading these two classes into the console application.

using System;
namespace AppDomainDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            MyClass1 obj1 = new MyClass1();
            MyClass2 obj2 = new MyClass2();

            Console.Read();
        }
    }

    public class MyClass1
    {
    }

    public class MyClass2
    {
    }
}

Now when you run the above application or EXE what will happen internally let us discuss. Here, the EXE runs as a Process inside the Operating System. Inside the Process, we have one App Domain by default loaded and inside that App Domain both the objects (obj1 and obj2) are running as shown in the below image.

App Domain in .NET Framework

Note: By default always there is an App Domain under which our .NET Code runs.

Need for App Domain in .NET Application:

Let us understand the need for Add Domain in .NET Application. Suppose you want to consume a Third Party DLL. That DLL you may get from the Internet or from any other third parties. Here, you have one doubt i.e. the Third Party DLL access your C:\ Drive. Suppose you want to use the Third DLL which you download from internet for reporting purpose, but there is some kind of virus which create a file in your C:/ Drive instead of working as a reporting tool.

Here, we are not downloading any DLL from the internet, instead, we will create a class as shown below which will act as the Third Party DLL.

Need for App Domain in .NET Application

Now, if you simply use the ThirdParty class with the default App Domain, then it can have access to your C:\ Drive. Let’s modify the Program.cs class file as shown below.

using System;
namespace AppDomainDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Third Party DLL
            ThirdParty Obj3 = new ThirdParty();

            //Own DLL
            MyClass1 obj1 = new MyClass1();
            MyClass2 obj2 = new MyClass2();

            Console.Read();
        }
    }

    [Serializable]
    public class ThirdParty
    {
        public ThirdParty()
        {
            Console.WriteLine("Third Party DLL Loaded");
            System.IO.File.Create(@"C:\xyz.txt");
        }

        ~ThirdParty()
        {
            Console.WriteLine("Third Party DLL Unloaded");
        }
    }
    
    public class MyClass1
    {
    }

    public class MyClass2
    {
    }
}

Now, when you execute the above code it will create the text file in the C Drive. But we want to restrict the third party DLL to access our C drive. We can do this by creating a separate App Domain for the Third Party DLL and then we will provide settings to that App Domain so that, it will not access our C Drive.

How to Create a Custom App Domain in .NET?

Let us see how to create our own App Domain and also see how we will run the Third Party DLL inside that App Domain. Then we will see how to provide permission to restrict access to the C Drive. Please have a look at the following image which shows how to create a custom app domain in C#. The code is self-explain, please go through the comment line.

How to Create a Custom App Domain in .NET?

Once you understood how to create a custom app domain in C#. Let us see what we want to do. We want to execute the Third Party DLLs using a custom App Domain while our classes we want to execute inside the default app domain which is shown in the below image.

How to Restrict Access a Custom App Domain to C Drive?

The complete code to implement the above requirement is given below.

using System;
namespace AppDomainDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create custom App Domain
            AppDomain customDomain = AppDomain.CreateDomain("customDomain");

            //Get the Type of ThirdParty
            Type thirdParty = typeof(ThirdParty);

            //Create object of ThirdParty using customDomain
            customDomain.CreateInstanceAndUnwrap(
                                  thirdParty.Assembly.FullName,
                                  thirdParty.FullName);

            //Unload the domain
            AppDomain.Unload(customDomain);
            
            //Own DLL
            MyClass1 obj1 = new MyClass1();
            MyClass2 obj2 = new MyClass2();

            Console.Read();
        }
    }

    [Serializable]
    public class ThirdParty
    {
        public ThirdParty()
        {
            Console.WriteLine("Third Party DLL Loaded");
            System.IO.File.Create(@"C:\xyz.txt");
        }

        ~ThirdParty()
        {
            Console.WriteLine("Third Party DLL Unloaded");
        }
    }
    
    public class MyClass1
    {
    }

    public class MyClass2
    {
    }
}

Now if you execute, then it will also create the text file in the C Drive. This is because we have run the Third Party DLL using a custom app domain but till now we have not written any logic to restrict access to C Drive.

How to Restrict Access a Custom App Domain to C Drive?

Let us see how to restrict the custom app domain to access our C Drive. In order to restrict the custom app domain to access C drive, we need to create a permission object and restrict No Access to C Drive and then create a setup for the app domain and finally, we need to use both permissions and set up while creating the custom app domain. The complete code is given below and the code is self-explain so, please go through the comment lines.

using System;
using System.Security;
using System.Security.Permissions;

namespace AppDomainDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create Permission object
            var permission = new PermissionSet(PermissionState.None);
            permission.AddPermission(
                new SecurityPermission(SecurityPermissionFlag.Execution)
                );

            //Set No Access to C drive
            permission.AddPermission(
               new FileIOPermission(FileIOPermissionAccess.NoAccess, @"C:\")
               );

            //Create setup for App Domain
            var setUp = new AppDomainSetup();
            setUp.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase; 

            //Create custom App Domain using the setup and permission
            AppDomain customDomain = AppDomain.CreateDomain("customDomain", null, setUp, permission);

            //Get the Type of ThirdParty
            Type thirdParty = typeof(ThirdParty);

            //Create object of ThirdParty using customDomain
            customDomain.CreateInstanceAndUnwrap(
                                  thirdParty.Assembly.FullName,
                                  thirdParty.FullName);

            //Unload the domain
            AppDomain.Unload(customDomain);
            
            //Own DLL
            MyClass1 obj1 = new MyClass1();
            MyClass2 obj2 = new MyClass2();

            Console.Read();
        }
    }

    [Serializable]
    public class ThirdParty
    {
        public ThirdParty()
        {
            Console.WriteLine("Third Party DLL Loaded");
            System.IO.File.Create(@"C:\xyz.txt");
        }

        ~ThirdParty()
        {
            Console.WriteLine("Third Party DLL Unloaded");
        }
    }
    
    public class MyClass1
    {
    }

    public class MyClass2
    {
    }
}

Now when you execute the above application, the line from which it will try to access and create a file in the C drive will through you an exception. But irrespective of the exception in custom app domain, if you want to execute the default app domain, then you need to put the logic of custom app domain inside the try-catch as shown in the below code.

using System;
using System.Security;
using System.Security.Permissions;

namespace AppDomainDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create Permission object
            var permission = new PermissionSet(PermissionState.None);
            permission.AddPermission(
                new SecurityPermission(SecurityPermissionFlag.Execution)
                );

            //Set No Access to C drive
            permission.AddPermission(
               new FileIOPermission(FileIOPermissionAccess.NoAccess, @"C:\")
               );

            //Create setup for App Domain
            var setUp = new AppDomainSetup();
            setUp.ApplicationBase = AppDomain.CurrentDomain.SetupInformation.ApplicationBase; 

            //Create custom App Domain using the setup and permission
            AppDomain customDomain = AppDomain.CreateDomain("customDomain", null, setUp, permission);

            try
            {
                //Get the Type of ThirdParty
                Type thirdParty = typeof(ThirdParty);

                //Create object of ThirdParty using customDomain
                customDomain.CreateInstanceAndUnwrap(
                                      thirdParty.Assembly.FullName,
                                      thirdParty.FullName);
            }
            catch(Exception ex)
            {
                //Unload the domain
                AppDomain.Unload(customDomain);
            }
            
            //Own DLL
            MyClass1 obj1 = new MyClass1();
            MyClass2 obj2 = new MyClass2();

            Console.Read();
        }
    }

    [Serializable]
    public class ThirdParty
    {
        public ThirdParty()
        {
            Console.WriteLine("Third Party DLL Loaded");
            System.IO.File.Create(@"C:\xyz.txt");
        }

        ~ThirdParty()
        {
            Console.WriteLine("Third Party DLL Unloaded");
        }
    }
    
    public class MyClass1
    {
    }

    public class MyClass2
    {
    }
}
Advantages of using App Domain in .NET Application:

The App Domain (Application Domain) is a logically isolated container inside a process. In this logical isolation, you can load and run .NET Code in an isolated manner. The following are the advantages of using the App Domain.

  1. You can load and unload DLL inside these logical containers without one container affecting the other. So, if there are issues in one application domain you can unload that application domain and the other application domain work without issues.
  2. If you have a Third Party DLL and for some reason, you don’t trust the third party code. You can run that DLL in an isolated app domain with fewer privileges. For example, you can say that the DLL cannot access to your “C:\” drive. And other DLLs that you trust you can run with full privilege in a different app domain.
  3. You can run different versions of DLL in every application domain.

In the next article, I am going to discuss the differences between Strong and weak assembly in .NET Framework with examples. Here, in this article, I try to explain the App Domain in .NET Framework with examples and I hope you enjoy this article.

Leave a Reply

Your email address will not be published. Required fields are marked *