class Program { static void Main(string[] args) { Console.WriteLine("***\r\n Begin program - logging with decorator\r\n"); IRepository<Customer> customerRepository =RepositoryFactory.Create<Customer>(); var customer = new Customer() { Id = 1, Name = "Customer 1", Address = "Address 1" }; customerRepository.Add(customer); customerRepository.Update(customer); customerRepository.Delete(customer); Console.WriteLine("\r\nEnd program - logging with decorator\r\n***"); Console.ReadLine(); } }
public class Customer { public int Id { get; set; } public string Name { get; set; } public string Address { get; set; } }
public interface IRepository<T> { void Add(T entity); void Delete(T entity); void Update(T entity); IEnumerable<T> GetAll(); T GetById(int id); }
public class Repository<T> : IRepository<T> { public void Add(T entity) { Console.WriteLine("Adding {0}", entity); } public void Delete(T entity) { Console.WriteLine("Deleting {0}", entity); } public void Update(T entity) { Console.WriteLine("Updating {0}", entity); } public IEnumerable<T> GetAll() { Console.WriteLine("Getting entities"); return null; } public T GetById(int id) { Console.WriteLine("Getting entity {0}", id); return default(T); } }
class DynamicProxy<T> : RealProxy { private readonly T _decorated; public DynamicProxy(T decorated) : base(typeof(T)) { _decorated = decorated; } private void Log(string msg, object arg = null) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(msg, arg); Console.ResetColor(); } public override IMessage Invoke(IMessage msg) { var methodCall = msg as IMethodCallMessage; var methodInfo = methodCall.MethodBase as MethodInfo; Log("In Dynamic Proxy - Before executing '{0}'",methodCall.MethodName); try { var result = methodInfo.Invoke(_decorated, methodCall.InArgs); Log("In Dynamic Proxy - After executing '{0}' ",methodCall.MethodName); return new ReturnMessage(result, null, 0,methodCall.LogicalCallContext, methodCall); } catch (Exception e) { Log(string.Format("In Dynamic Proxy- Exception {0} executing '{1}'", e),methodCall.MethodName); return new ReturnMessage(e, methodCall); } } }
public class RepositoryFactory { public static IRepository<T> Create<T>() { var repository = new Repository<T>(); var dynamicProxy = new DynamicProxy<IRepository<T>>(repository); return dynamicProxy.GetTransparentProxy() as IRepository<T>; } }