Autofac Dependency Injection with Simple Class using MVC Web API

Autofac Dependency Injection with Simple Class using MVC Web API 


Add class library called - Project.Business

Add class - TestSimpleService

public class TestSimpleService
{
 public string GetPing()
 {
  return "simple class called";
 }
}
 


Add WebAPI Project called Project.API

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


Add Controller - TestController

public class TestController : ApiController
{
 TestSimpleService testService;
 public TestController(TestSimpleService _testService)
 {
  testService = _testService;
 }

 [HttpGet]
 [Route("CallSimple")]
 public HttpResponseMessage GetPing()
 {
  var ping = testService.GetPing();
  return Request.CreateResponse(HttpStatusCode.OK, ping);
 }
}
 
 

  

Add class AutofacConfigs.cs

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

  //Add Simple class  mapping
   builder.RegisterType<TestSimpleService>().AsSelf().InstancePerRequest();

  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