I appologize if this is a possible duplication, I’ve looked everywhere and couldn’t find an answer.
My question is more of a “best practice/convention”-sort of question.
So here is my situation, I’m having an AccountController -> something like this:
public AccountController(IAuthenticationHelper authHelper,
IAccountService accountService)
{
_authHelper = authHelper;
_accountService = accountService;
}
In my _Layout view, I have a placeholder for the currently logged in account. In order to get the currently logged in account, I’m retrieving the current user identity from the HttpContext (which I have in a wrapper class so I can unit test it) -> then I’m getting the account details from the DB.
Now here is my question, I need this data In the _Layout, I could possibly do a partial view expecting an account model -> place it in the _Layout … And here is where I get stuck, I don’t like the idea of so many trips to the database, and I don’t like the fact that I have to think about this small detail from within all Actions ? Am I missing something here, am I thinking of this wrong ? Did I got the concept wrong ? What’s the right way to do this ? (In a testable manner, preferably).
Help is much appreciated !
EDIT: I’ll be happy to provide with more code, if required.
You could use
Child actionsto achieve that. For example you will have a specific controller dedicated to retrieving the currently logged user details and pass them to a partial view:Then of course you will have a corresponding partial view to display the user information.
And from your _Layout you could render this child action:
And of course to avoid multiple roundtrips to the database you could simple cache this information.
Now your main actions and models don’t have to worry about this common functionality. It is handled by the child action. Obviously you have the possibility to use Dependency Injection in the
UserInfoControllerto make it perfectly unit testable.