A day with .Net

My day to day experince in .net

Dependency injection WEB API and Ninject.

Posted by vivekcek on September 28, 2013

In this post i will explain how to inject dependency to Web Api controller using Ninject.

1. Create a basic MVC application.

2. In the Model folder add an interface and its implementation as given below.

 public interface IMyInterface
    {
        string Name { get; set; }
    }
public class MyClass:IMyInterface
    {
        public string Name
        {
            get
            {
                return "vivek";
            }
            set
            {
                this.Name = value;
            }
        }
    }

3. Through Nuget add Ninject for MVC 3 as shown below. This package is designed for MVC. This package will also install Ninject core and Ninject webCommon.

1

4. After installation go to App_Start folder. You can see a new class named ‘NinjectWebCommon.cs’ is created. Open this class.

2

5. Inside the class Under the RegisterServices() method add the mapping of your interface to implementation.

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

6. Go to Nuget again and add ‘Ninject.WebApi.DependencyResolver’.

3

7. In the NinjectWebCommon.cs file undel CreateKernal() method add the below code.

System.Web.Http.GlobalConfiguration.Configuration.DependencyResolver = new Ninject.WebApi.DependencyResolver.NinjectDependencyResolver(kernel);

4

8. Now add Web Api controller

 public class WebApiController : ApiController
    {
        private IMyInterface _iMyInterface = null;

        public WebApiController(IMyInterface iMyInterface)
        {
            _iMyInterface = iMyInterface;
        }

        [HttpGet]
        public string GetName()
        {
            return _iMyInterface.Name;
        }
    }

9. Now call the Web Api in google chrome ‘http://localhost:58956/api/WebApi/GetName‘.You can saw the below result.

5

Advertisements

One Response to “Dependency injection WEB API and Ninject.”

  1. ES said

    Doesn’t work foe MVC 4 and WEB API 2, got an error:
    Could not load file or assembly ‘System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35’ or one of its dependencies. The system cannot find the file specified.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s