Reputation: 8252
I am looking at creating a user context per request. Something like this, but it just feels wrong:
container.Register<UserContext>(() =>
{
var context = new UserContext();
//add runtime data...
return context;
});
And then inject it into a base service layer class for reuse.
Can anyone point me in a better direction to accomplish this?
Thanks in advance.
Upvotes: 2
Views: 1417
Reputation: 172835
The construction of object graphs should be reliable, so we can construct them with confidence. This basically means that we shouldn't construct them using runtime data.
HttpContext
and its properties are runtime data, and accessing it during object graph construction:
causes ambiguity, complicates the composition root with an extra responsibility and makes it extraordinarily hard to verify the correctness of your DI configuration.
The solution is to refactor UserContext
in such way that HttpContext
is only accessed when one of its members (other than the constructor) is accessed. This allows the UserContext
to be constructed without knowledge about the request and even allows it to become stateless and singleton. The referenced article shows an example of such implementation:
class HttpSessionUserContext : IUserContext
{
public int CurrentUserId => (int)HttpContext.Session["userId"];
}
Upvotes: 3