.net – Responding to application-killing events during class initialization – Education Career Blog

When starting my application, I have a couple of classes which are required to read certain files in order to create a set of default data.

The logical place (to me) to do this is in a Shared class constructor; the idea would be to throw a class-level event if the reading of the defaults file fails. Unfortunately, this does not work as attempting to access such an event, in order to attach a handler to it, fires the class constructor before the event has been attached. In a failing case, the constructor starts, fires the fail event, the constructor completes, and then the event handler is attached, after the event has fired.

The only other solution I can think of is to give the class a “typeInitialisedSuccessfully” boolean property and put a try/catch block around every call to construct an instance of the class, which seems unnecessarily kludgey to me.

Can someone suggest a more elegant solution?

EDIT: Because this is a fundamental Class, used in one form or another across nearly all of our software tools, I would greatly prefer a solution that will notify future programmers that the type initialiser needs to be called, which is why I initially went towards the Shared Constructor as a solution.

,

I would suggest having an Init (can be static) method on your classes. You would run this method on your application start for each of your classes-to-be-initialized. In that case you can wrap it in try catch and act accordingly.

Re your edit:
Generally throwing exceptions in places like shared constructor is bad idea – you can’t really catch it, it’s hard to predict when the init will be called etc.

In case you specify I’d add either IsInitialized field that would be checked and an exception thrown when calling method/property that requires it. It can get tedious though.

The other option I would go for might be far from your current architecture. In many IoC tools they use concept of Startable (castle, autofac) – i.e. you specify an interface with a start method and the IoC will make sure the method runs at specified time (most likely when application is started). You would do your error handling in your ‘Start’ method and bubble up whatever wrapped exception with all the detailed information.
I could elaborate on this but I have feeling it’s not really the way you would go.

Leave a Comment