0

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?

2 Answers 2

4

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();
}
Sign up to request clarification or add additional context in comments.

4 Comments

I was afraid that this would be the only way. It's grotesque to say the least. I only like to have this logic occur once in the entire application if I can help it; Doing it more than once kind of defeats the purpose of SoC. But, if this is the only choice we have then so be it. Thanks for the answer :)
Yes. You try to decouple stuff using IoC and then have to go back to some kind of service locator and similar anti-patterns. This is one of the issues I have with static methods. Thank Microsoft for that one ;) Glad I could help!
Yeah. The only alternative I can think of is to use a web service instead of a code behind web method because I can do property injection on a web service but the logic in this web method is isolated to a single page and is only used once. Seems silly to have an entire web service for one method, but that's probably better than an injection anti-pattern. If only we were using MVC.
The method Jason alluded to below seemed to make more sense to me, but after trying both, I found this method to be much more elegant. Better to have this ugliness than a global static class.
-1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.