Created
September 12, 2012 14:32
-
-
Save gists-app-test/3707013 to your computer and use it in GitHub Desktop.
Ninject MVC bind constructor arguments to HttpContext.Current.Session
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Foo : IFoo | |
{ | |
string _applicationName; | |
string _currentUserName; | |
public Foo(string applicationName, string currentUserName) | |
{ | |
_applicationName = applicationName; | |
_currentUserName = currentUserName; | |
} | |
public void Bar() | |
{ | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface IFoo | |
{ | |
void Bar(); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public static class NinjectMVC3 | |
{ | |
//Other bootstrapper methods removed to be more concise | |
private static void RegisterServices(IKernel kernel) | |
{ | |
kernel.Bind<IFoo>().To<Foo>() | |
.WithConstructorArgument("applicationName", "value1") | |
.WithConstructorArgument("currentUserName", x => GetSessionValue("UserName")); | |
} | |
static string GetSessionValue(string key) | |
{ | |
if (HttpContext.Current == null) return ""; | |
var httpSessionStateBase = new HttpContextWrapper(HttpContext.Current).Session; | |
if (httpSessionStateBase != null && httpSessionStateBase[key] != null) | |
return httpSessionStateBase[key].ToString(); | |
return ""; | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I tried using this .It works fine for the first call during that request However in subsequent call the session values are returned Null.