C # Run code before constructor

I would like to automatically execute some code before any class constructor is executed (to load some externall assmebly that the class needs), all in C #, .NET 2.0

EDIT:

public class MyClass { ThisTypeFromExternalAssembly variable; } 

And I really need to have an assembly loader that is somehow tied to MyClass in order to load the externall assembly when necessary. This should happen before the constructor, but I would not want to call some Init() before constructing the MyClass() object

+4
source share
4 answers

You can use a static initializer for the class:

 static ClassName( ) { } 

This will be called before all instances of ClassName are created.

Given the update you would do:

 public class MyClass { ThisTypeFromExternalAssembly variable; static MyClass( ) { InitialiseExternalLibrary( ); } public MyClass( ) { variable = new ThisTypeFromExternalAssembly( ); } } 
+5
source

Could you use a static constructor ?

 class SimpleClass { // Static constructor static SimpleClass() { //... } } 

From an MSDN article:

A static constructor is used to initialize any static data or to perform a specific action that needs to be performed only once. This is called automatically until the first instance is created or statically members are referenced.

+4
source

If it loads the assembly, it sounds like you just want to do it once, in which case a static constructor might be worthwhile:

 public class Foo { static Foo() { // Load assembly here } } 

Note that if this fails (throws an exception), the type will be unusable in AppDomain .

Is there a reason why you are not just using regular type permission to load an assembly? Will the assembly load automatically when you need to use it? Could you give more detailed information about the problem you are trying to solve?

+3
source

you can use an aop framework like postsharp, which allows you to interfere with a function call using attributes.

http://www.sharpcrafters.com/solutions/monitoring#tracing

Postsharp: how does it work?

http://www.codeproject.com/KB/cs/ps-custom-attributes-1.aspx

0
source

Source: https://habr.com/ru/post/1341810/


All Articles