Ninject per session singleton?

2019-03-16 23:21发布

问题:

So I'm trying to introduce the concept of a user to my application and have got my own set of custom login routines etc. working fine. In my module, I'm binding my IUserSession to my implementation and InSingletonScope.

Now I suspect this was the case and have been able to prove that this is not the right thing to do, if I try and login with two users against the same site, I get only one set of data.

If I implement a MembershipProvider, do I avoid such a restriction. I know that if I implement a membership provider, I don't have to inject everything, but my login isn't just a username/password, how do go about logging in with additional data"?

回答1:

InSingletonScope is shared across the entire application not limited per user session. Nothing you do will change that. You need to use something else like InRequestScope but that's only shared per actual request...

Try this site: http://iridescence.no/post/Session-Scoped-Bindings-With-Ninject-2.aspx

public static class NinjectSessionScopingExtention {
    public static void InSessionScope<T>(this IBindingInSyntax<T> parent) {
        parent.InScope(SessionScopeCallback);
    }

    private const string _sessionKey = "Ninject Session Scope Sync Root";

    private static object SessionScopeCallback(IContext context) {
        if (HttpContext.Current.Session[_sessionKey] == null) {
            HttpContext.Current.Session[_sessionKey] = new object();
        }

        return HttpContext.Current.Session[_sessionKey];
    }
}