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.