Console Application Prestart

405 views Asked by At

Is there any attribute similar to WebActivatorEx.PreApplicationStartMethod (webActivatorEx dll) for console applications implemented in .NET 4.5 . Or is it possible to create one? I would like to create an attribute, that will make a method execute before the console application's main method is executed. I would not like to use Postsharp or any similar library that does not come with the .NET 4.5 framework.

1

There are 1 answers

0
Venemo On

There is no way you can do this without having to modify the Main function itself or at least the class which contains the Main function.

I don't see why you would want to do this. Why not simply add some code to the start of your Main? Perhaps you could be more specific in your question with regards to what exactly you are trying to achieve.

Static constructor

The simplest way I could think of is to create a static constructor for the class which contains the Main method. That will be executed before the Main method is called.

Custom attribute

You can create a custom attribute, but it won't work without you writing some code that explicitly searches for stuff that has that attribute. See the MSDN articles on writing custom attributes and retrieving information stored in attributes.

So an attribute doesn't actually do anything by itself. In order for it to work, you need to use Reflection. The PreApplicationStartMethodAttribute works the same way: the framework explicitly searches for this attribute and executes the method through Reflection.

If this is what you want to do, you need to:

  • Create a custom attribute
  • Write some code in your Main that looks for that attribute and executes the method specified.

Although I don't see why you would need such a thing in a console app.