I am trying to figure out how (if it is even possible), to initialize a class once in a controller with parameter so that I don't have to create an instance in each method. I am getting back a bearer token that I need to submit with each call. This works:
public string token
{
get { return (HttpContext.Session["AccessToken"] != null) ? HttpContext.Session["AccessToken"].ToString() : ""; }
set { HttpContext.Session["AccessToken"] = value; }
}
public async Task<ActionResult> Index()
{
Client client = new Client();
string token = await client.GetToken("TFBiUWxBU2trZnh;lkjlkj;lTZXRIfFN5ZWR8NjcwNzg=");
Session["AccessToken"] = token;
return View();
}
public async Task<ActionResult> About()
{
Client client = new Client(token);
var employees = await client.GetEmployees();
return View();
}
I get the token and save it in a session variable then use it to create a new Client(token)
. What I am trying to find out if there is a way to create something like this:
public Client _client = new Client(token);
at the top of the controller so that I don't have to keep creating a new instance in every method. I tried doing the following:
public string token
{
get { return (HttpContext.Session["AccessToken"] != null) ? HttpContext.Session["AccessToken"].ToString() : ""; }
set { HttpContext.Session["AccessToken"] = value; }
}
Client Client;
public HomeController()
{
Client = new Client(token);
}
but then the Session throws a System.NullReference.Exception. It seems there should be a way to do this, but I can't figure it out.
CodePudding user response:
Your HttpContext.Session
isn't initialized by the time the constructor runs.
It seems like you're actually looking for a get-only property though.
public Client _client => new Client(token);
// This is shorthand for the following
public Client _client { get { return new Client(token); } }
If you truly only want one, persistent instance, then you'll have to only create the client once the session has been initialized.