c# – ASP.net 4.6 MVC 5每个会话的Autofac对象

在我的ASP.net MVC应用程序中,我想为每个会话应“导出”的对象设置一个值.我试过这样的:

我想要的对象:

    public class Core : ICore {

    public Core() {
        UserSession = new UserSession();
    }

    public UserSession UserSession { get; set; }
}

Global.asax中:

protected void Application_Start() {

        var builder = new ContainerBuilder();
        //register ICore
        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);
    }

我将值设置为对象的位置(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) {
                // Set Value
                _core.UserSession.CurrentUser = user;

                return RedirectToAction("Index", "Home");
            }
        }
        return View(form);
    }
}

我需要此Session对象的位置

同一申请中的第一名:
(这里ICore不为null,但我之前在Controller中设置的CurrentUser为null)

    public class ClaimsAuthorize : AuthorizeAttribute {

    public ICore Core { get; set; }

    protected override bool AuthorizeCore(HttpContextBase httpContext) {
        //Here is CurrentUser null
        var currentUser = Core.UserSession.CurrentUser;
        return currentUser != null;
    }
}

另一个项目中的第二个(SQL上下文):

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;
    }
}

最佳答案 在您的global.asax中,您可以像这样注册ICore:

builder.Register(c =>
{
    if (HttpContext.Current == null)
    {
        throw new Exception("no httpcontext available");
    }

    ICore core = HttpContext.Current.Session["ICore"] as ICore;
    if (core == null)
    {
        core = new Core();
        HttpContext.Current.Session["ICore"] = core;
    }

    return core;
}).As<ICore>();

在这种情况下,每次Autofac将解析ICore时,它将查看会话并在需要时向其添加新实例.

点赞