开发者

Can I Add a handler to AppDomain.CurrentDomain.UnhandledException in a class library

I want to subscribe to the AppDomain.CurrentDomain.UnhandledException event to catch any error开发者_如何学Pythons as im trying a new design pattern where I dont want to put a try catch on every event.

usually in a win forms app there is a main entry point, but this is a class library that is called by another application.

Is there a main entry point in a class library where I can hook up this event, or is it just not possible in a class library unless im sure one method will get called before anything else?


No, class libraries don't have a main entry point. If you feel like you need one, then you could conceptually create one virtually via your public API surface area. In other words, limit what objects are public and in those public objects make sure the call gets made at some point. That could be taken to the extreme of requiring a factory call of some kind to setup your library before doing anything.


// Set the unhandled exception mode to force errors to go through our handler. 
Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

// Add the event handler for handling thread exceptions to the event.
AppDomain.CurrentDomain.UnhandledException += 
    new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

Thanks to Brian Dishaw

Clearly this does not give you some non declarative way of assigning the handler, ala assingning a trace listener in app.config but, that gives me an idea.

You could write your own configuration section that would perform this code. Then when the config is loaded you could assign the event handler, I'll find some links on how to do that ...

However, your configuration would have to be present in the main app so perhaps this is not right.

EDIT Sorry, I don't think there is way to do this without a IoC framework of some kind, what else would load your class. The only options I can think of all require some sort of change to the main application.

I'm interested in being wrong.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜