Ninject inject a service interface in a web service

I have a web service in my project that I use to return json data to ajax calls.

Injecting my ClientService works fine on regular pages but how do I get it to work in the Web Service?

NinjectWebCommon.cs:

 private static void RegisterServices(IKernel kernel)
        {
            kernel.Bind<IClientService>().To<ClientService>();
        }

Default.aspx.cs: works!

public partial class _Default : System.Web.UI.Page
    {
 [Inject]
        public IClientService clientService { get; set; }

MyWebservice.asmx: NullReferenceException (clientService is null)

 public class MyWebService: System.Web.Services.WebService
    {     
        [Inject]
        public IClientService clientService { get; set; } 


 [WebMethod, ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public MyObject GetClients(int id)
        {
            var list = clientService.GetClients(id);

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

I have solved this problem. I changed MyWebService class to derive from Ninject.Web.WebServiceBase:

public class MyWebService: WebServiceBase

Method 2

I run on the same problem. Took me a while to figure it out.
My solution to this problem is adding statatic Ninject instantiation of Kernel in Global.asax :

  public class Global : NinjectHttpApplication 
    {
        private static Ninject.IKernel kernel = new Ninject.StandardKernel();

        protected override Ninject.IKernel CreateKernel()
        {

            //Business TI
            kernel.Bind<IYourService>().To<YourService>();

            return kernel;
        }
}

What enables to get it directly from singleton(public) or which solution I choosed, by accesing NinjectHttpApplication’s context :
//in webservice parameterless constructor

yourService = ((NinjectHttpApplication)HttpContext.Current.ApplicationInstance).Kernel.Get<IPublicationService>();

This is the solution for working with legacy asmx web service, putting aside


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x