"
ASP.NET (snapshot 2017) Microsoft documentation and samples

Dependency Injection in ASP.NET Web API 2

by Mike Wasson

Download Completed Project

This tutorial shows how to inject dependencies into your ASP.NET Web API controller.

Software versions used in the tutorial

What is Dependency Injection?

A dependency is any object that another object requires. For example, it’s common to define a repository that handles data access. Let’s illustrate with an example. First, we’ll define a domain model:

[!code-csharpMain]

   1:  public class Product
   2:  {
   3:      public int Id { get; set; }
   4:      public string Name { get; set; }
   5:      public decimal Price { get; set; }
   6:  }

Here is a simple repository class that stores items in a database, using Entity Framework.

[!code-csharpMain]

   1:  public class ProductsContext : DbContext
   2:  {
   3:      public ProductsContext()
   4:          : base("name=ProductsContext")
   5:      {
   6:      }
   7:      public DbSet<Product> Products { get; set; }
   8:  }
   9:   
  10:  public class ProductRepository : IDisposable
  11:  {
  12:      private ProductsContext db = new ProductsContext();
  13:   
  14:      public IEnumerable<Product> GetAll()
  15:      {
  16:          return db.Products;
  17:      }
  18:      public Product GetByID(int id)
  19:      {
  20:          return db.Products.FirstOrDefault(p => p.Id == id);
  21:      }
  22:      public void Add(Product product)
  23:      {
  24:          db.Products.Add(product);
  25:          db.SaveChanges();
  26:      }
  27:   
  28:      protected void Dispose(bool disposing)
  29:      {
  30:          if (disposing)
  31:          {
  32:              if (db != null)
  33:              {
  34:                  db.Dispose();
  35:                  db = null;
  36:              }
  37:          }
  38:      }
  39:   
  40:      public void Dispose()
  41:      {
  42:          Dispose(true);
  43:          GC.SuppressFinalize(this);
  44:      }
  45:  }

Now let’s define a Web API controller that supports GET requests for Product entities. (I’m leaving out POST and other methods for simplicity.) Here is a first attempt:

[!code-csharpMain]

   1:  public class ProductsController : ApiController
   2:  {
   3:      // This line of code is a problem!
   4:      ProductRepository _repository = new ProductRepository();
   5:   
   6:      public IEnumerable<Product> Get()
   7:      {
   8:          return _repository.GetAll();
   9:      }
  10:   
  11:      public IHttpActionResult Get(int id)
  12:      {
  13:          var product = _repository.GetByID(id);
  14:          if (product == null)
  15:          {
  16:              return NotFound();
  17:          }
  18:          return Ok(product);
  19:      }
  20:  }

Notice that the controller class depends on ProductRepository, and we are letting the controller create the ProductRepository instance. However, it’s a bad idea to hard code the dependency in this way, for several reasons.

We can address these problems by injecting the repository into the controller. First, refactor the ProductRepository class into an interface:

[!code-csharpMain]

   1:  public interface IProductRepository
   2:  {
   3:      IEnumerable<Product> GetAll();
   4:      Product GetById(int id);
   5:      void Add(Product product);
   6:  }
   7:   
   8:  public class ProductRepository : IProductRepository
   9:  {
  10:      // Implementation not shown.
  11:  }

Then provide the IProductRepository as a constructor parameter:

[!code-csharpMain]

   1:  public class ProductsController : ApiController
   2:  {
   3:      private IProductRepository _repository;
   4:   
   5:      public ProductsController(IProductRepository repository)  
   6:      {
   7:          _repository = repository;
   8:      }
   9:   
  10:      // Other controller methods not shown.
  11:  }

This example uses constructor injection. You can also use setter injection, where you set the dependency through a setter method or property.

But now there is a problem, because your application doesn’t create the controller directly. Web API creates the controller when it routes the request, and Web API doesn’t know anything about IProductRepository. This is where the Web API dependency resolver comes in.

The Web API Dependency Resolver

Web API defines the IDependencyResolver interface for resolving dependencies. Here is the definition of the interface:

[!code-csharpMain]

   1:  public interface IDependencyResolver : IDependencyScope, IDisposable
   2:  {
   3:      IDependencyScope BeginScope();
   4:  }
   5:   
   6:  public interface IDependencyScope : IDisposable
   7:  {
   8:      object GetService(Type serviceType);
   9:      IEnumerable<object> GetServices(Type serviceType);
  10:  }

The IDependencyScope interface has two methods:

The IDependencyResolver method inherits IDependencyScope and adds the BeginScope method. I’ll talk about scopes later in this tutorial.

When Web API creates a controller instance, it first calls IDependencyResolver.GetService, passing in the controller type. You can use this extensibility hook to create the controller, resolving any dependencies. If GetService returns null, Web API looks for a parameterless constructor on the controller class.

Dependency Resolution with the Unity Container

Although you could write a complete IDependencyResolver implementation from scratch, the interface is really designed to act as bridge between Web API and existing IoC containers.

An IoC container is a software component that is responsible for managing dependencies. You register types with the container, and then use the container to create objects. The container automatically figures out the dependency relations. Many IoC containers also allow you to control things like object lifetime and scope.

[!NOTE] “IoC” stands for “inversion of control”, which is a general pattern where a framework calls into application code. An IoC container constructs your objects for you, which “inverts” the usual flow of control.

For this tutorial, we’ll use Unity from Microsoft Patterns & Practices. (Other popular libraries include Castle Windsor, Spring.Net, Autofac, Ninject, and StructureMap.) You can use NuGet Package Manager to install Unity. From the Tools menu in Visual Studio, select Library Package Manager, then select Package Manager Console. In the Package Manager Console window, type the following command:

[!code-consoleMain]

   1:  Install-Package Unity

Here is an implementation of IDependencyResolver that wraps a Unity container.

[!code-csharpMain]

   1:  using Microsoft.Practices.Unity;
   2:  using System;
   3:  using System.Collections.Generic;
   4:  using System.Web.Http.Dependencies;
   5:   
   6:  public class UnityResolver : IDependencyResolver
   7:  {
   8:      protected IUnityContainer container;
   9:   
  10:      public UnityResolver(IUnityContainer container)
  11:      {
  12:          if (container == null)
  13:          {
  14:              throw new ArgumentNullException("container");
  15:          }
  16:          this.container = container;
  17:      }
  18:   
  19:      public object GetService(Type serviceType)
  20:      {
  21:          try
  22:          {
  23:              return container.Resolve(serviceType);
  24:          }
  25:          catch (ResolutionFailedException)
  26:          {
  27:              return null;
  28:          }
  29:      }
  30:   
  31:      public IEnumerable<object> GetServices(Type serviceType)
  32:      {
  33:          try
  34:          {
  35:              return container.ResolveAll(serviceType);
  36:          }
  37:          catch (ResolutionFailedException)
  38:          {
  39:              return new List<object>();
  40:          }
  41:      }
  42:   
  43:      public IDependencyScope BeginScope()
  44:      {
  45:          var child = container.CreateChildContainer();
  46:          return new UnityResolver(child);
  47:      }
  48:   
  49:      public void Dispose()
  50:      {
  51:          Dispose(true);
  52:      }
  53:   
  54:      protected virtual void Dispose(bool disposing)
  55:      {
  56:          container.Dispose();
  57:      }
  58:  }

[!NOTE] If the GetService method cannot resolve a type, it should return null. If the GetServices method cannot resolve a type, it should return an empty collection object. Don’t throw exceptions for unknown types.

Configuring the Dependency Resolver

Set the dependency resolver on the DependencyResolver property of the global HttpConfiguration object.

The following code registers the IProductRepository interface with Unity and then creates a UnityResolver.

[!code-csharpMain]

   1:  public static void Register(HttpConfiguration config)
   2:  {
   3:      var container = new UnityContainer();
   4:      container.RegisterType<IProductRepository, ProductRepository>(new HierarchicalLifetimeManager());
   5:      config.DependencyResolver = new UnityResolver(container);
   6:   
   7:      // Other Web API configuration not shown.
   8:  }

Dependency Scope and Controller Lifetime

Controllers are created per request. To manage object lifetimes, IDependencyResolver uses the concept of a scope.

The dependency resolver attached to the HttpConfiguration object has global scope. When Web API creates a controller, it calls BeginScope. This method returns an IDependencyScope that represents a child scope.

Web API then calls GetService on the child scope to create the controller. When request is complete, Web API calls Dispose on the child scope. Use the Dispose method to dispose of the controller’s dependencies.

How you implement BeginScope depends on the IoC container. For Unity, scope corresponds to a child container:

[!code-csharpMain]

   1:  public IDependencyScope BeginScope()
   2:  {
   3:      var child = container.CreateChildContainer();
   4:      return new UnityResolver(child);
   5:  }

Most IoC containers have similar equivalents.



Comments ( )
Link to this page: //www.vb-net.com/AspNet-DocAndSamples-2017/aspnet/web-api/overview/advanced/dependency-injection.htm
< THANKS ME>