pepemadruga
pepemadruga

Reputation: 55

Always call static constructor

Is there a way of calling the constructor of a static class always? After searching, I've seen that it is call only once.

I have a class with many methods, mine is like 20 methods, but let's imagine the class has 500 methods. These 500 methods have all of them a call to a webservice. Now, before the call to the webservice I have to do a security check with certificates (due to changes in servers):

ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateRemoteCertificate);
CredentialCache cache = new CredentialCache();

So I have to write that code before each call. All the methods are static, as well as the class, so my options are:

Is there a way to call the static construcor always? I've seen something about Aspects, but not really sure how to use them.

Upvotes: 0

Views: 831

Answers (4)

user3021830
user3021830

Reputation: 2924

yIf you would like to perform a security check, I would suggest the use of Singleton pattern. You can make a security check at tthe private constructor, but be aware that this this will be ridiculously wrong.

It will only make security check for the first call, then will reside in memory and won't necessarily perform a security check for other calls.

Upvotes: 0

toadflakz
toadflakz

Reputation: 7944

Use a Singleton instance of the class instead of either instantiated or static class instance.

You get the power of the instantiated class but can use it like a static class meaning your issue with repetitive code is resolved and you can use it like a static class in that your single instance is available as a static property.

Implementing Singleton in C#

Upvotes: 0

Justin
Justin

Reputation: 86729

No

A static constructor can only be called once and is intended only for initialization, not for logic (such as authentication)

Upvotes: 2

Patrick Hofman
Patrick Hofman

Reputation: 156948

static constructors are meant to run only once. You are not going to change that.

The best solution is, as you stated, to create an instance of your class and put that code that needs to be ran again in the constructor. It seems to me though that certificate checks need to be done once, since the certificate won't change in a few seconds.

Upvotes: 4

Related Questions