Search code examples
c#asp.net-mvcaspnetboilerplate

How to execute a service in Global's Session_Start()


I currently have a asp.net mvc application with ABP implementation. I currently want to execute a service method inside the Session_Start(), may I ask how abouts would I do that.

The service can be executed anywhere I have access to the IOC resolve but I'm in the global file and I'm not entirely sure how to do that from there.

protected void Session_Start()
{
    // starting a session and already authenticated means we have an old cookie
    var existingUser = System.Web.HttpContext.Current.User;
    if (existingUser != null && existingUser.Identity.Name != "")
    {
        // execute app service here.
        // if I'm exposed to IOCresolver I would do the following below
        var srv = _iocResolver.Resolve<SettingsAppService>();
        srv.UpdateItems();
    }
}

May I ask how do I access IOC resolver on global.asax.cs file, if even possible. My goal is to execute the service when the user has re-established his session.


Solution

  • From the documentation on Dependency Injection:

    The IIocResolver (and IIocManager) also have the CreateScope extension method (defined in the Abp.Dependency namespace) to safely release all resolved dependencies.

    At the end of using block, all resolved dependencies are automatically removed.

    If you are in a static context or can not inject IIocManager, as a last resort, you can use a singleton object IocManager.Instance everywhere.

    So, use a scope with IocManager.Instance:

    • using (var scope = IocManager.Instance.CreateScope()) { ... }
      IocManager.Instance.UsingScope(scope => { ... })
    protected void Session_Start()
    {
        // Starting a session and already authenticated means we have an old cookie
        var existingUser = System.Web.HttpContext.Current.User;
        if (existingUser != null && existingUser.Identity.Name != "")
        {
            IocManager.Instance.UsingScope(scope => // Here
            {
                // Execute app service here.
                var srv = scope.Resolve<SettingsAppService>();
                srv.UpdateItems();
            });
        }
    }