30 Kasım 2018

The Ambient Context Design Pattern in .NET

The Ambient Context Design Pattern in .NET
using System;
using System.Collections.Generic;
namespace DependencyInjection
{
    class Program
    {
        static void Main(string[] args)
        {

            PrintContextTitle();
            using (new MyNestedContext("outer scope"))
            {
                PrintContextTitle();
                using (new MyNestedContext("inner scope"))
                {
                    PrintContextTitle();
                }
                PrintContextTitle();
            }
            PrintContextTitle();

            Console.ReadKey();
        }

        static void PrintContextTitle()
        {
            Console.WriteLine("Current Context is {0}", MyNestedContext.Current != null ? MyNestedContext.Current.Title : "null");
        }
    }

    
    public class MyNestedContext : IDisposable
    {
        private static Stack<MyNestedContext> scopeStack = new Stack<MyNestedContext>();

        public string Title { get; set; }
        public MyNestedContext(string title)
        {
            Title = title;
            scopeStack.Push(this);
        }

        public static MyNestedContext Current {
            get {
                if (scopeStack.Count == 0)
                    return null;
                return scopeStack.Peek();
            }
        }
        public void Dispose()
        {          
            scopeStack.Pop();
        }       
    }
}