In my ASP.net MVC application, I want to set a value for an object that should be "exported" per session. I tried like this:
The object I want:
public class Core : ICore {
public Core() {
UserSession = new UserSession();
}
public UserSession UserSession { get; set; }
}
global.asax:
protected void Application_Start() {
var builder = new ContainerBuilder();
builder.RegisterType<Core.Core>().As<ICore>().InstancePerLifetimeScope();
builder.RegisterControllers(typeof (MvcApplication).Assembly);
builder.RegisterFilterProvider();
var container = builder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
BundleConfig.RegisterBundles(BundleTable.Bundles);
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
The place where I set the value for the object (UserController):
public class UserController : BaseController {
private readonly ICore _core;
private readonly IUserDomain _userDomain;
public UserController(ICore core, IUserDomain userDomain) {
_core = core;
_userDomain = userDomain;
}
[HttpPost]
[AllowAnonymous]
public ActionResult Login(LoginForm form) {
if (ModelState.IsValid) {
var user = _userDomain.GetByName(form.Username);
if (user != null) {
_core.UserSession.CurrentUser = user;
return RedirectToAction("Index", "Home");
}
}
return View(form);
}
}
Places where I need this session object
1st in the same application:
(Here, ICore is not null, but CurrentUser, which I installed earlier in the controller, is null)
public class ClaimsAuthorize : AuthorizeAttribute {
public ICore Core { get; set; }
protected override bool AuthorizeCore(HttpContextBase httpContext) {
var currentUser = Core.UserSession.CurrentUser;
return currentUser != null;
}
}
2nd in another project (SQL Context):
public class BaseContext <TModel> where TModel : BaseModel {
protected readonly ICore Core;
protected NHibernateSession NHibernateSession;
public BaseContext(ICore core) {
Core = core;
}
public virtual bool Save(TModel model) {
if (Core.UserSession.CurrentUser == null) {
return false;
}
model.CreatedBy = Core.UserSession.CurrentUser.Id;
model.CreatedAt = DateTime.Now;
using (var session = NHibernateSession.SessionFactory.OpenSession()) {
using (var transaction = session.BeginTransaction()) {
session.Save(model);
transaction.Commit();
}
}
return true;
}
}
public class PageContext : BaseContext<Page>, IPageContext {
public PageContext(ICore core, NHibernateSession nHibernateSession) : base(core) {
NHibernateSession = nHibernateSession;
}
}
source
share