Reputation: 15
I need to "wrap" C# methods to set and initialize variables. The wrapper has to do something BEFORE and AFTER the wrapped method. Just as a basic example, I'd like to do something like:
public void foo()
{
Console.WriteLine("inside foo");
}
public void silly_wrapper(string ham)
{
// somethig before
Console.WriteLine(ham + "before" );
DateTime tic = DateTime.Now; //Current Date
// call function
foo();
// something after
TimeSpan time = DateTime.Now - tic; //Current Date
Console.WriteLine(ham + $"after in {time}");
}
I have to repeat this on almost ALL my methods. Actually I want to call an Initialize()
method after all the constructors of all the classes in my project.
Is there any way to do it in a smarter way? I've tried to implement Attribute but there is no way to call something after the method.
[mywrapperFunction("spam")]
public void foo()
{
Console.WriteLine("inside foo");
}
Generalizing the wrapper with a Func
argument is going to be a mess (too many options) and I'm supposed to call every function inside the wrapper function.
Upvotes: 1
Views: 408
Reputation: 117055
You need to look up Aspect Oriented Programming (AOP) en.wikipedia.org/wiki/Aspect-oriented_programming in C#. Or, potentially, dependency injection with the decorator pattern as an alternative to AOP. Either way, it's hard. You should rely on your memory.
However, a simple approach that may work for you is this:
public static class Wrapper
{
public static void Call(string ham, Action action)
{
Console.WriteLine(ham + "before");
var sw = Stopwatch.StartNew();
action();
sw.Stop();
Console.WriteLine(ham + $"after in {sw.Elapsed}");
}
public static T Call<T>(string ham, Func<T> func)
{
Console.WriteLine(ham + "before");
var sw = Stopwatch.StartNew();
var t = func();
sw.Stop();
Console.WriteLine(ham + $"after in {sw.Elapsed}");
return t;
}
}
Now you'd still have to remember, but your code now looks like this:
Wrapper.Call("Inside foo", foo);
Upvotes: 1