如何通过网络方法访问变量? [英] How to access my variables in a web method?

查看:46
本文介绍了如何通过网络方法访问变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ASP.NET Webforms,并且在一页中,我想在后面的代码中对Web方法进行AJAX调用.问题是Web方法是静态的,我无法访问页面变量.我需要能够让Ninject注入依赖项.是否可以通过网络方法执行此操作?

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

由于Web方法是静态的,因此甚至无法将其包含在页面的代码中似乎很愚蠢,因为它实际上无法与页面进行交互.在后面的代码中,这是一个孤立的孤岛.有没有更好的方法可以做到这一点?还是至少有一种方法可以让Ninject以某种方式将ISecurityController注入到Web方法中?

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?

感谢您的帮助.

推荐答案

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

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

这篇关于如何通过网络方法访问变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆