1

I have a 3 tiered architecture (Controller/Service/Repository) as well as a Domain for models that all layers will need. Each layer includes the domain, and each layer includes it's "parent" layer. So Repository -> Service -> Api

enter image description here

When a request comes into the Api, some authentication and authorization is done. Multiple organizations share the same tables, so this auth also includes the scoped organization information. I am calling this the ApiContext. Since this information is resolved in the Api Layer, it's not accessible to the higher layer levels.

Generally I've seen people use the HttpContext here to pass the request context up but I'm trying to keep the service and repository layers from including WebApi.

To get the ApiContext up the chain, I'm thinking about using ThreadContext where the ApiContext has a Current field that is set by a request filter.

class ApiContext {
  [ThreadStatic]
  public static ApiContext Current;
}

I'm not familiar with ThreadContext but I'm pretty sure HttpContext uses it so I think I should be using it.

Questions about ThreadContext.

Will using async methods break ThreadContext? Will using Thread.Run(() => {}) break ThreadContext? Is there any reason why I shouldn't use ThreadContext here?

micah
  • 7,596
  • 10
  • 49
  • 90
  • 2
    A useful read on this exact topic https://www.hanselman.com/blog/ATaleOfTwoTechniquesTheThreadStaticAttributeAndSystemWebHttpContextCurrentItems.aspx, basic summary ***"Don't slap a [ThreadStatic] attribute on a static member when you're operating within ASP.NET as chances are you don't control the thread life"***, I think [AsyncLocal](https://msdn.microsoft.com/en-us/library/dn906268(v=vs.110).aspx) will solve your problem, but I have never personally used it so I don't feel confidant posting it as an answer. – Scott Chamberlain Sep 02 '17 at 16:18
  • Interesting. So because of this limitation you wouldn't lose sleep importing System.Web into all layers of the application? – micah Sep 02 '17 at 16:28
  • 1
    If I knew the library was only ever going to be used with a web project, not at all. – Scott Chamberlain Sep 02 '17 at 16:29
  • I'd consider this the accepted answer if you wanted to make your comment that answer. This helps a lot – micah Sep 02 '17 at 16:34
  • Feel free to post your own answer and accept it – Scott Chamberlain Sep 02 '17 at 22:46

0 Answers0