Dependency Injection example in WebAPI



1)What is Dependency Injection, What is the use of it? 

-Dependency Injection is design pattern help us to develop loosely coupled code.
-Loosely coupled components need not know much details about the components to use it.
 

2)What is dependency graph ?

-Dependency Graph is the collection of objects that must be created in ordered to request root object.

3) What is the DI Container (or ) IOC container in ASP.NET Core?

-DI container responsible creation of an instance of service.
-This container knows how to create an instance including all its dependencies and passing these to constructor.

4) How many ways inject the dependency?

1)Using constructor 
2)Using Property 

Using constructor is re commanded.

Example:
using System.Web.Http.Dependencies;

Creating Dependency Dependency Resolver

 public class CustomResolver : IDependencyResolver, IDependencyScope
{
 public object GetService(Type serviceType)
{         
 return serviceType == typeof(IRepository)? new StudentRepository() : null;     
 }
}

Registering  the Dependency Resolver

public static class WebApiConfig
{     
public static void Register(HttpConfiguration config)
{
--------------------------------
---------------------------------         
config.DependencyResolver = new CustomResolver();   
  }

  }
Implementing in class


  public class StudentController : ApiController
{
 private IRepository Repository { get; set; }
public StudentController()
{       
  Repository = (IRepository)GlobalConfiguration.Configuration.DependencyResolver.GetService(typeof(IRepository));     

}
}

Thanks for visiting this blog. How is the content?. Your comment is great gift to my work. Cheers.

No comments:

Post a Comment