Skip to content

Instantly share code, notes, and snippets.

@hahmed
Created June 23, 2011 08:52
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hahmed/1042173 to your computer and use it in GitHub Desktop.
Save hahmed/1042173 to your computer and use it in GitHub Desktop.
IUserSession for asp.net mvc application...
My service defintion held inside my services layer - no access to web app
public interface IUserSession
{
void LogOut();
string GetUsername();
LoggedonuserDTO GetCurrentUser();
}
My implementation of this method that IS held inside my web app, is where i want my Kernal to hold this implementation so I can get access to it later on in any service methods or controllers.
public class UserSession : IUserSession
{
private readonly IAuthorizationService _authenticationService;
public UserSession(IAuthorizationService authenticationService)
{
_authenticationService = authenticationService;
}
private string Username
{
get
{
if (HttpContext.Current.User != null)
return HttpContext.Current.User.Identity.Name;
else
throw new NoAccessException();
}
}
public LoggedonuserDTO GetCurrentUser()
{
var identity = HttpContext.Current.User.Identity;
if (!identity.IsAuthenticated)
return null;
var user = _authenticationService.GetLoggedOnUser(Username);
if (user == null)
throw new NoAccessException();
return user;
}
public void LogOut()
{
HttpContext.Current.User = null;
FormsAuthentication.SignOut();
}
public string GetUsername()
{
return Username;
}
}
Binding is done in Global.asax
// using NInject to override application started
protected override void OnApplicationStarted()
{
AreaRegistration.RegisterAllAreas();
// hand over control to NInject to register all controllers
RegisterRoutes(RouteTable.Routes);
Container.Get<ILoggingService>().Info("Application started");
Container.Bind<IUserSession>().To<UserSession>().InRequestScope(); //here is the binding...
}
Usage scenario:
Note: I want to access IUserSession maybe in any other service call e.g. IEmailService may have IUserSession passed into the ctor e.g.
public EmailService : IEmailService
{
private readonly IUserSession _session;
public EmailService(IUserSession _session)
{
this._session = _session;
}
public void SendMail()
{
console.writeline(_session.GetUsername());// this should work...
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment