2

In my master layout page, I need to access a SessionManager instance simply to display which user is logged in.

I have it working as follows (_Layout.cshtml):

@using Ninject
@{
    var kernel = new StandardKernel();
    var sm = kernel.Get<SessionManager>();
}
<!DOCTYPE html>
<html>
   ...
   etc...

Then further down I use the instance like this:

<p>Logged in as @(sm.LoggedInUser.Name)</p>

Now this works, but is this untidy? Can I do this in a better way? Is it OK to create an instance of StandardKernel like this (I assume it's a singleton)?

I thought about making all controllers inherit from a base controller, and injecting the SessionManager into the base controller, but it seems slightly over the top.

Laurence Frost
  • 2,759
  • 3
  • 28
  • 45
  • 1
    Views should not be concerned of things such as session-management and Ninject kernels. You better use a `ViewModel` or override the `User` property with your custom `IPrincipal` type that will provide the necessary information (http://stackoverflow.com/a/10524305). As of controllers, yes, injecting `SessionManager` into controller (or base controller) is fine. – haim770 Nov 10 '15 at 15:25
  • Thanks for your response. I agree that Views should not be responsible for this, but how can a ViewModel help here? It's not really a view - it's a master page which views slot into. It's not feasible to populate a VM for every action just to allow the layout to display who is logged in. – Laurence Frost Nov 10 '15 at 16:44
  • That's why I suggested the second solution – haim770 Nov 10 '15 at 16:45

1 Answers1

4

Normally NInject MVC extension plugs into MVC's Dependency Resolver infrastructure, and you should be able to resolve your services via it:

var sm = DependencyResolver.Current.GetService<SessionManager>();
ovolko
  • 2,777
  • 2
  • 21
  • 26