Autofac Dependency Injection with MVC Web API

Autofac Dependency Injection with MVC Web API

Add Class library called - Project.Data

Add Entity Data Model - .edmx and select your database table and add it in edmx fie (For me I am adding Employee table)

Add Interface name => IEmployeeData

public interface IEmployeeData
  {
   List<Employee> GetEmployees();
  }
 

Add Simple class EmployeeData and inherite interface

public class EmployeeData : IEmployeeData
  {
   public List<Employee> GetEmployees()
   {
    List<Employee> employees;
    using (var db = new DemoEntities())
    {
     employees = db.Employees.ToList();
    }
    return employees;
   }
  }
 

  

Add class library called - Project.Business

Add Inteface - IEmployeeService

public interface IEmployeeService
  {
   List<Employee> GetEmployees();
  }



Add Simple class EmployeeData and inherite interface

public class EmployeeService : IEmployeeService
{
 IEmployeeData employeeData;
 public EmployeeService(IEmployeeData _employeeData)
 {
  employeeData = _employeeData;
 }
 public List<Employee> GetEmployees()
 {
  return employeeData.GetEmployees();
 }
}

  

Add WebAPI Project called Project.API

Add nuget packages => Autofac, Autofac.WebApi2 and EntityFramework

Add ConnectionString in web.config file


Add Controller - EmployeeController

public class EmployeeController : ApiController
    {
        IEmployeeService employeeService;
        public EmployeeController(IEmployeeService _employeeService)
        {
            employeeService = _employeeService;
        }

        [HttpGet]
        [Route("employees")]
        public HttpResponseMessage GetEmployees()
        {
            var employees = employeeService.GetEmployees();
            return Request.CreateResponse(HttpStatusCode.OK, employees);
        }
    }
 

  

Add class AutofacConfigs.cs

public class AutofacConfigs
{
 public static void Configure()
 {
  var builder = new ContainerBuilder();
  builder.RegisterApiControllers(Assembly.GetExecutingAssembly()); 

  //Add Service mapping
  builder.RegisterType<EmployeeService>().As<IEmployeeService>();

  //Add data mapping
  builder.RegisterType<EmployeeData>().As<IEmployeeData>();

  var container = builder.Build();
  var resolver = new AutofacWebApiDependencyResolver(container);
  GlobalConfiguration.Configuration.DependencyResolver = resolver;
 }
}

 

  

register this class application start
protected void Application_Start()
{
AutofacConfigs.Configure();
// ... other configuration

}


Run application

Hope this will help you and save your time.

Enjoy !!!

:)

No comments:

Post a Comment