How to access my variables in a web method?

∥☆過路亽.° 提交于 2021-02-05 11:14:07

问题


I am using ASP.NET Webforms and in one page I want to make an AJAX call to a web method in the code behind. The problem is that web methods are static and I can't access page variables. I need to be able to have Ninject inject a dependency. Is there a way to do this in a web method?

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.
    }
}

Since web methods are static it almost seems silly to even have it in the code behind for the page because it can't actually interact with the page. It's an isolated island in the code behind. Is there a better way to accomplish this? Or at the very least is there a way I can have Ninject inject ISecurityController into the web method somehow?

Thanks for the help.


回答1:


You can directly retrieve it from the kernel using the IKernel.Get<T>() method:

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



回答2:


somwhere in your application is a singleton of Ninject. reference this singleton within the webmethod. a similar process is being do in Ninject.Web.PageBase.



来源:https://stackoverflow.com/questions/8839352/how-to-access-my-variables-in-a-web-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!