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

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

我目前有一个 asp.net 带有 ABP 实现的 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 解析器,如果可能的话。我的目标是在用户重新建立会话时执行服务。

您可以为 IoC 解析器创建静态 link 并在 Global.asax 中使用它。您甚至可以将其添加到 Global.asax.cs。在容器注册后设置此 属性 并在任何地方使用它。

public static YourIocResolver IocResolver { get; set; }

来自 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.

因此,使用范围 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();
        });
    }
}