开发者

C# Execute code before constructor

I'd like to automagically execute some code before certain class constructor gets executed (to load some externall assmebly that class requires), all in C#, .NET 2.0

EDIT:

public class MyClass 
{
    ThisTypeFromExternalAssembly variable;
}

And what I really need is to have assembly loader 开发者_JS百科that is 'attached' somehow to MyClass, to load externall assembly when it is needed. This must happen before constructor, but I would not like to need to call some Init() before constructing MyClass() object


You can use the static initialiser for the class:

static ClassName( )
{

}

This will be called before any instances of ClassName are constructed.

Given the update you would do:

public class MyClass
{
    ThisTypeFromExternalAssembly variable;

    static MyClass( )
    {
        InitialiseExternalLibrary( );
    }

    public MyClass( )
    {
         variable = new ThisTypeFromExternalAssembly( );
    }
}


Could you use a static constructor for this?

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

From the MSDN article:

A static constructor is used to initialize any static data, or to perform a particular action that needs performed once only. It is called automatically before the first instance is created or any static members are referenced.


If it's to load an assembly, that sounds like you just want to do it once, in which case a static constructor may be appropriate:

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

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

Is there any reason why you're not just using normal type resolution to load the assembly though? Wouldn't the assembly be loaded automatically when you need to use part of it? Could you give more details about the problem you're trying to solve?


you might want to use an aop framework like postsharp, which allows to interfere function call by 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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜