如何在Global的Session_Start()中执行服务

时间:2019-01-18 17:24:58

标签: c# asp.net-mvc aspnetboilerplate

我目前有一个带有ABP实现的asp.net mvc应用程序。我目前想在Session_Start()内部执行一个服务方法,请问我该怎么做。

该服务可以在我有权访问IOC解析的任何位置执行,但是我在全局文件中,因此我不确定如何从那里执行该操作。

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();
    }
}

请问如果可能的话,如何访问global.asax.cs文件上的IOC解析器。我的目标是在用户重新建立会话后执行服务。

2 个答案:

答案 0 :(得分:0)

You can create a static link to your IoC resolver and use it in Global.asax. You even can add it to Global.asax.cs. Set this property after container registration and use it from anywhere.

public static YourIocResolver IocResolver { get; set; }

答案 1 :(得分:0)

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();
        });
    }
}