using System;
using System.Threading;
namespace DynamicWrapperTest
{
public class Payment
{
public Guid Id { get ; set ; }
public Guid UserId { get ; set ; }
public Guid OperationId { get ; set ; }
public decimal Amount { get ; set ; }
public string Description { get ; set ; }
}
public class PaymentService
{
private readonly Random rand = new Random (Environment.TickCount);
public void MakePayment(Payment payment)
{
Thread.Sleep( TimeSpan .FromSeconds(rand.Next(5)));
}
}
}
* This source code was highlighted with Source Code Highlighter .
using System;
using System.Dynamic;
namespace DynamicWrapperTest
{
public class DynamicWrapper : DynamicObject
{
private readonly object source;
public DynamicWrapper( object source)
{
this .source = source;
}
public override bool TryInvokeMember(InvokeMemberBinder binder, object [] args, out object result)
{
var methodInfo = source.GetType().GetMethod(binder.Name);
if (methodInfo != null )
{
Func< object , object [], object > func = (s, a) => methodInfo.Invoke(s, a);
result = MethodCall(func, source, args);
return true ;
}
result = null ;
return false ;
}
protected virtual object MethodCall(Func< object , object [], object > func, object src, object [] args)
{
return func(src, args);
}
}
}
* This source code was highlighted with Source Code Highlighter .
using System;
using System.Diagnostics;
using System.IO;
namespace DynamicWrapperTest
{
public class ProfilerWrapper : DynamicWrapper
{
private readonly int iterationCount;
private readonly TextWriter output;
private readonly Stopwatch stopwatch = new Stopwatch();
public ProfilerWrapper( object source, int iterationCount, TextWriter output)
: base (source)
{
this .iterationCount = iterationCount;
this .output = output;
}
protected override object MethodCall(Func< object , object [], object > func, object src, object [] args)
{
object result = null ;
for ( var i = 0; i < iterationCount; i++)
{
stopwatch.Restart();
result = base .MethodCall(func, src, args);
stopwatch.Stop();
output.WriteLine( "Step #{0} : Method call in {1} ms" , i + 1, stopwatch.Elapsed.TotalMilliseconds);
}
return result;
}
}
}
* This source code was highlighted with Source Code Highlighter .
using System;
namespace DynamicWrapperTest
{
class Program
{
static void Main( string [] args)
{
var payment = new Payment
{
Id = Guid .NewGuid(),
UserId = Guid .NewGuid(),
OperationId = Guid .NewGuid(),
Amount = 500m,
Description = "Feed developers plz!!!"
};
var paymentService = new PaymentService();
dynamic dynamicWrapper = new ProfilerWrapper(paymentService, 10, Console .Out);
dynamicWrapper.MakePayment(payment);
Console .ReadKey();
}
}
}
* This source code was highlighted with Source Code Highlighter .
Source: https://habr.com/ru/post/120294/