I want to have access to user properties for an authenticated user, such as UserId and FirstName, without querying the database each time. I found this site through a post on Stack Overflow, and I like this approach, but I use IoC / repositories and decided not to try to get global .asax to communicate with the database, fearing that it will not be compatible with the repository template.
Instead, I created an interface for CustomPrincipal, and I use IoC (Castle) to instantiate and pass it to the controllers (and then to the base controller).
The base controller uses the methods I created in CustomPrincipal to accomplish the same task as the blog author in global.asax. Namely, CustomPrincipal is initialized from a database or cache and assigned to HttpContext.Current.User.
My controllers / views can then reference the properties as follows:
((ICustomPrincipal)(HttpContext.Current.User)).FirstName;
This works, but I feel some smells of code. First of all, if I refer to the HttpContext from the controllers, I killed unit testing. I'm thinking of modifying my CustomPrincipal object to return the above value (such that I can mock it in my unit tests), but I'm wondering if this is a workaround, not a good solution.
Am I going to do it right? Are there any small tricks that I can do to make this a reliable solution, or should I start from scratch using a FormsAuthenticationTicket or something like that?
Thank!
Mayo source
share