0

I want to create common objects (Logger, database context, ...etc) just one time for each user, more precisely create the object when the user first requests a method in my Web API service and then use the same object created instead of creating and initializing the same object every call to my service.

Is there a way to do this?

IAmInPLS
  • 4,051
  • 4
  • 24
  • 57
Moha med
  • 89
  • 8
  • And by "user" I assume you mean request? Or do you really mean once per authenticated user? – CodingGorilla Apr 05 '16 at 13:28
  • once per authenticated user – Moha med Apr 05 '16 at 13:30
  • I would suggest using sessions then, this post might be helpful to you: http://stackoverflow.com/questions/9594229/accessing-session-using-asp-net-web-api – CodingGorilla Apr 05 '16 at 13:36
  • 3
    Sessions are the antithesis of Web Api. If you utilize sessions you're fundamentally violating REST. Frankly, why do you feel the need to do this anyways? Keep a per-request lifecycle on these types of objects is the best practice. There's no logical reason you would *need* to persist something like a context across multiple requests, and it's actually dangerous to do so. A logger may be less offensive, but what do you really gain by persisting over newing it up again for each request. At the best this would be a micro-optimization. – Chris Pratt Apr 05 '16 at 13:47
  • @ChrisPratt : you mean that using sessions will make the service not REST? – Moha med Apr 05 '16 at 14:12
  • REST is stateless by definition. Sessions persist a state between requests, and are, obviously, stateful. A service which is not stateless is therefore not a RESTful service. – Federico Dipuma Apr 05 '16 at 14:16

0 Answers0