简体   繁体   中英

How can I get/create an instance of an object on Simple Injector container depending on the asp.net web api 2 session?

I have an asp.net web api 2 project in which I register a singleton LoginData

containerLocal.RegisterSingleton<ILoginData>(
    () => new LoginData { LanguageCode = null, UserCode = null });

What I want to do is when a user log in to the app I register an instance of that Login data in my container

var loginData = AppContainer.Container.GetInstance<ILoginData>();

loginData.UserCode = userData.Username;
loginData.LanguageCode = "es";

and then, on whatever controller get that instance of user to perform any operation

my problem is that when I try to make a get request from 2 different browsers I get the last instance of Login data created in the app instead of the instance with the correct user

[Route("stock/menu")]
[HttpGet]
public async Task<IHttpActionResult> Menu()
{
    var loginData = AppContainer.Container.GetInstance<ILoginData>();
    return Ok(loginData);
}

example:

  • Login in chrome browser with username 'foo'
  • Make get request on InventarioMenu in chrome (gets LoginData with user 'foo')
  • Login in firefox browser with username 'bar'
  • Make get request on InventarioMenu in firefox (gets LoginData with user 'bar')
  • Make get request on InventarioMenu in chrome (gets LoginData with user 'bar')

There are multiple ways to solve this. A possible solution is to make an ILoginData implementation that stores information in a Session:

public sealed class SessionLoginData : ILoginData
{
    public string UserCode
    {
        get { (string)this.Session[nameof(UserCode)]; }
        set { this.Session[nameof(UserCode)] = value; }
    }

    public string LanguageCode
    {
        get { (string)this.Session[nameof(LanguageCode)]; }
        set { this.Session[nameof(LanguageCode)] = value; }
    }

    private HttpSessionState Session => HttpContext.Current.Session;
}

Since this class itself contains no state (but delegates that to the HttpContext.Session ), this implementation can be registered as singleton:

container.RegisterSingleton<ILoginData, SessionLoginData>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM