2

Is it possible to define your own ambient classes?

For example, the TransactionScope class makes itself available to any object which implements IEnlistmentNotification (I think), without any code to explicitly pass a reference of one object to the other.

I'm not sure if I'd ever need to use this, but it would be interesting to understand how it worked (i.e. how I could implement such functionality in my own code). Is this something we can build into our own classes, or was something developed at a lower level to allow TransactionScope to do something beyond what's available at the "regular developer" level?

JohnLBevan
  • 22,735
  • 13
  • 96
  • 178

1 Answers1

2

Writing new TransactionScope() just sets the static Transaction.Current property.

Other classes can check whether this property is not null and enlist themselves in the transaction.

There is no magic involved.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
  • Ahh, for some reason I hadn't thought of that; I guess because the libraries which can take part in this are so disparate I'd assumed there was no way for them to share information. Thanks @Slaks. I'm kind of disappointed by the lack of magic though. – JohnLBevan Oct 21 '12 at 00:56
  • @JohnLBevan: IMHO, magic in libraries is evil. Except for core thiungs like strings, arrays, and reflection, you could duplciate everything in the .Net class libraries. There is (almost) no magic anywhere. – SLaks Oct 21 '12 at 00:57
  • True - it tends to lead to unexpected behaviour; magic goes against the rules of consistency. – JohnLBevan Oct 21 '12 at 01:03
  • Transaction.Current is marked with the ThreadStatic attribute, which is arguably a magical attribute. – ZunTzu Sep 05 '14 at 13:52
  • @ZunTzu: But's it's an attribute you can use yourself. You can also duplicate the effect with a `ConditionalWeakTable`. – SLaks Sep 05 '14 at 15:00
  • @SLaks. It is true you can use ThreadStatic yourself. My intention was just to point out that Transaction.Current is not a simple static property and that the underlying mechanism - in which JohnsLBevan seems interested - relies on the peculiarities of ThreadStatic - which predates ConditionalWeakTable. – ZunTzu Sep 08 '14 at 09:54
  • 1
    As @ZunTzu mentioned the "magic" is related to `[ThreadStatic]`. If you're visiting this in 2018, then you should check out [AsyncLocal](https://learn.microsoft.com/en-us/dotnet/api/system.threading.asynclocal-1?view=netframework-4.7.2) – nqramjets Oct 23 '18 at 20:17