如何在web方法中访问我的变量

本文关键字:访问 我的 变量 方法 web | 更新日期: 2023-09-27 18:20:04

我正在使用ASP.NET Webforms,在一个页面中,我想在代码后面对web方法进行AJAX调用。问题是web方法是静态的,我不能访问页面变量。我需要能够让Ninject注入一个依赖项。有没有一种方法可以在web方法中做到这一点?

public partial class Default : Ninject.Web.PageBase
{
    [Inject]
    public ISecurityController SecurityController { get; set; }

    [WebMethod]
    public static string DoSomething()
    {
        SecurityController.WriteToLog(); // Can't access SecurityController because it doesn't exist.
    }
}

由于web方法是静态的,因此将其包含在页面的代码中似乎很愚蠢,因为它实际上无法与页面交互。这是代码背后的一个孤岛。有更好的方法来实现这一点吗?或者至少有没有一种方法可以让Ninject以某种方式将ISecurityController注入到web方法中?

谢谢你的帮助。

如何在web方法中访问我的变量

您可以使用IKernel.Get<T>()方法直接从内核中检索它:

[WebMethod]
public static string DoSomething()
{
    NinjectModule module = new YourModule();
    IKernel kernel = new StandardKernel(module);
    var controller = kernel.Get<ISecurityController>();
    controller.WriteToLog();
}

应用程序中的somware是Ninject的一个单例。在web方法中引用这个单例。Ninject.Web.PageBase.

中也有类似的过程