Using ThreadContext instead of HttpContext?

290 views Asked by At

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?

0

There are 0 answers