Using Ninject dependency injection in WebApi

Posted by sfmnetsys on Tue, 07 Apr 2020 19:17:54 +0200

Ninject dependency injection was used in MVC before, and recently in WebApi. It was found that interface injection was used in the previous MVC mode, which has always been a Null error. Some resources were queried on the Internet, and they will be used later.

It is mainly divided into the following steps:

  1. Install Ninject.MVC on nuget. I installed Ninject.MVC5 on nuget
  2. Two classes, NinjectScope and NinjectResolver, are defined to implement the IDependencyResolver required by the latest version of Web Api
  3. Add the following code to Global
 protected void Application_Start()
        {
       
            //Set up ApiController injection
            GlobalConfiguration.Configuration.DependencyResolver = new  NinjectResolver(CreateKernel());

            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
      /// <summary>
        ///Interface mapping
        /// </summary>
        /// <returns></returns>
        public IKernel CreateKernel()
        {
            var Kernel = new StandardKernel();
            Kernel.Bind<IUser>().To<User>();
        
            return Kernel;
        }    

4. At the place of use, call as follows

    

   public class StudentController : ApiController
    {


        [Ninject.Inject]
        public IResource resource { get; set; }
        [Ninject.Inject]
        public IUser user { get; set; }


        [HttpPost]
        [AllowAnonymous]
        public object Login([FromBody] UserModel model)
        {
            var model = user.GetLogin(model.UserCode, EncryptPwd, sysRole);
        
        }
}

  

 public class NinjectScope: IDependencyScope
    {
                    protected IResolutionRoot
             resolutionRoot;

                    public NinjectScope(IResolutionRoot
             kernel)
                    {
                        resolutionRoot
             = kernel;
                    }

                    public object GetService(Type
             serviceType)
                    {
                        IRequest
             request = resolutionRoot.CreateRequest(serviceType, null,
            new Parameter[0],
            true,
            true);
                        return resolutionRoot.Resolve(request).SingleOrDefault();
                    }

                    public IEnumerable<object>
             GetServices(Type serviceType)
                    {
                        IRequest
             request = resolutionRoot.CreateRequest(serviceType, null,
            new Parameter[0],
            true,
            true);
                        return resolutionRoot.Resolve(request).ToList();
                    }

                    public void Dispose()
                    {
                        IDisposable
             disposable = (IDisposable)resolutionRoot;
                        if (disposable
             != null)
                            disposable.Dispose();
                        resolutionRoot
             = null;
                    }
    }

  

 public class NinjectResolver
   : NinjectScope, IDependencyResolver
    {
        private IKernel
         _kernel;
        public NinjectResolver(IKernel
         kernel)
        :
        base(kernel)
        {
            _kernel
             = kernel;
        }
        public IDependencyScope
         BeginScope()
        {
            return new NinjectScope(_kernel.BeginBlock());
        }
    }

Topics: ASP.NET