Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Database.Log is not an event? [closed]

Entity Framework recently added the ability to capture the SQL queries with the Database.Log hook.

What surprised me is that it is not implemented as a "protected encapsulation-friendly armored" delegate, a.k.a an event, but as a bare multicast delegate.

And indeed I've seen members of the EF team doing this:

context.Database.Log = sql => Debug.WriteLine(sql);

Where I'd expect:

context.Database.Log += sql => Debug.WriteLine(sql);

to avoid erasing previous registered handlers.

Moreover with a bare delegate we can call it directly:

context.Database.Log("SORRY SQL IS TOO MEDIEVAL FOR ME");

Which of course is not something I'd expect to do.

Is there some rationales behind this choice or the original developer missed a coffee break and forgot to add the event keyword before committing. ;)

EDIT : all of a sudden I have a really terrible doubt: as a .Net practitioner and trainer I've "measured" that 97% of .Net devs are convinced that events MUST be EventHandlers, so if I was auditing a "normal" company source code I would think: it's OK, the guy does not know it can use any delegate type and for simplicity (we only need to transfer a string) didn't want to use an EventHandler so he thought he couldn't use and event so instead used a bare delegate without considering encapsulation "issues". But this would be for a "normal" company and I think it's highly improbable from a Microsoft developer...

like image 524
Pragmateek Avatar asked Jul 12 '14 17:07

Pragmateek


1 Answers

That is merely per-instance logging in case you quickly want to create output for one specific DbContext instance, and not to create generic logger for entire application.

If you want to log everything and set it on the application level, then you need to implement IDbCommandInterceptor:

MSDN Article

You can have as many interceptors as you like and use dbContext.Database.Log as well at the same time.

like image 200
Admir Tuzović Avatar answered Nov 07 '22 21:11

Admir Tuzović