c# - StackOverflow exception (fundamental architecture flaw) -
i'm using lazy singleton next jon skeet's great pattern here.
the purpose of object provide references of other methods in application.
for example, gettheme(context.current.user.id)
gets theme current user, plethora of other methods.
the issue i'm running how deal changes in state when object instantiated?
namely, if user comes website , isn't logged in, context
object used during creation of new user.
however, after logging in, user
object null, because instantiated.
i've tried deal in next way, making public property reference private method checks null
reference, , tries determine if should indeed null
.
unfortunately, turns infinite loop , crashes every time.
i have tried making user object lazy, unusual reason doesn't instantiate when called , remains null
.
what i'm looking is, how create user
property of lazy singleton evaluate when called, , instantiate if it's null
, capable of beingness populated?
the conditions being, mvc global user
object property user.identity.name
not null, , passed session @ load pulled in model, , user exists in database using username key.
public sealed class context { public static context current { { homecoming lazy.value; } } private static readonly lazy<context> lazy = new lazy<context>(() => new context()); public usermeta user { { homecoming _meta(); } } private context() { deployment = getcurrentdeploymenttype(); device = (device)httpcontext.current.session["currentdevice"]; } private usermeta _meta() { //if current object null, //but user has been authenticated, populate object if (current.user == null && !string.isnullorempty((string)httpcontext.current.session["useremail"])) { //check user in database first var _usertry = sql.read.userbyemail((string)httpcontext.current.session["useremail"]); if (_usertry == null) { homecoming new usermeta( new usermeta((string)httpcontext.current.session["useremail"])); } homecoming null; } //if current instance has populated user object, //just utilize else if (current.user != null) homecoming current.user; else homecoming null; } }
if utilize private field, solve problem
public sealed class context { private usermeta _user = null; public static context current { { homecoming lazy.value; } } private static readonly lazy<context> lazy = new lazy<context>(() => new context()); public usermeta user { { if (_user == null) _user =_meta(); homecoming _user; } } private context() { private usermeta _meta() { if (!string.isnullorempty((string)httpcontext.current.session["useremail"])) { //check user in database first var _usertry = sql.read.userbyemail((string)httpcontext.current.session["useremail"]); if (_usertry == null) { homecoming new usermeta( new usermeta((string)httpcontext.current.session["useremail"])); } homecoming null; } }
c# design-patterns singleton stack-overflow lazy-evaluation
No comments:
Post a Comment