Advertisement

Advertisement

How to use Autofac DI(Dependency Injection) in asp.net MVC 5

How to use Autofac DI(Dependency Injection) in asp.net MVC 5

Autofac is a powerful dependency injection container that you can use in both ASP.NET MVC Framework (MVC 5) and ASP.NET Core applications. Below is a step-by-step guide on how to use Autofac in an ASP.NET MVC 5 application:


1. Install Autofac and Autofac.Mvc5

Use NuGet Package Manager to install Autofac:

Install-Package Autofac Install-Package Autofac.Mvc5

This will add the necessary libraries to your project.


2. Create a Dependency Resolver

You need to configure Autofac as the dependency resolver for your application. This is done in the Global.asax file.

  1. Add the following namespaces:

    using Autofac; using Autofac.Integration.Mvc; using System.Web.Mvc;
  2. Update Application_Start in Global.asax:

    protected void Application_Start() { // Register routes, bundles, etc. AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); // Autofac container setup var builder = new ContainerBuilder(); // Register controllers builder.RegisterControllers(typeof(MvcApplication).Assembly); // Register your application dependencies (e.g., DbContext, services) builder.RegisterType<StudentContext>().AsSelf().InstancePerRequest(); // Build the container var container = builder.Build(); // Set Autofac as the dependency resolver DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); }

3. Modify Your Controller

Refactor your controller to use constructor injection:

Before:

public class HomeController : Controller { StudentContext db = new StudentContext(); public ActionResult Index() { var students = db.Students.ToList(); return View(students); } }

After:

public class HomeController : Controller
{ private readonly StudentContext _db; // Constructor Injection public HomeController(StudentContext db) { _db = db; } public ActionResult Index() { var students = _db.Students.ToList(); return View(students); } }

Autofac will automatically inject the StudentContext instance when creating the HomeController.


4. Register Other Dependencies

If you have custom services, you can register them in Autofac too.

Example:

  1. Create an interface and implementation:


    public interface IStudentService { List<Student> GetAllStudents(); } public class StudentService : IStudentService { private readonly StudentContext _context; public StudentService(StudentContext context) { _context = context; } public List<Student> GetAllStudents() { return _context.Students.ToList(); } }
  2. Register the service in the Autofac container:


    builder.RegisterType<StudentService>().As<IStudentService>().InstancePerRequest();
  3. Use the service in a controller:

    public class HomeController : Controller { private readonly IStudentService _studentService; public HomeController(IStudentService studentService) { _studentService = studentService; } public ActionResult Index() { var students = _studentService.GetAllStudents(); return View(students); } }

5. Benefits of Using Autofac

  • Decoupling: You can easily replace implementations without changing the dependent code.
  • Testability: You can inject mock objects into your controllers for testing.
  • Flexibility: Autofac supports advanced features like property injection, modules, and lifetime scopes.

6. Advanced Features

  • InstancePerRequest: Ensures one instance per HTTP request.
  • InstancePerDependency: Creates a new instance each time it's requested.
  • SingleInstance: Creates a singleton instance shared across the application.

Example:

builder.RegisterType<MySingletonService>().As<IMyService>().SingleInstance();

Autofac Di

Complete Example

Here’s the final setup:

Global.asax:

protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); var builder = new ContainerBuilder(); // Register controllers builder.RegisterControllers(typeof(MvcApplication).Assembly); // Register DbContext builder.RegisterType<StudentContext>().AsSelf().InstancePerRequest(); // Register a service builder.RegisterType<StudentService>().As<IStudentService>().InstancePerRequest(); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); }

Controller:

public class HomeController : Controller { private readonly IStudentService _studentService; public HomeController(IStudentService studentService) { _studentService = studentService; } public ActionResult Index() { var students = _studentService.GetAllStudents(); return View(students); } }

Conclusion

By integrating Autofac, you:

  1. Use constructor injection to decouple dependencies.
  2. Register dependencies in a central place (Global.asax).
  3. Simplify testing and enhance maintainability.

Let me know if you need more help setting this up!

How to use Autofac DI(Dependency Injection) in asp.net MVC 5 How to use Autofac DI(Dependency Injection) in asp.net MVC 5 Reviewed by Rikesh on November 22, 2024 Rating: 5

No comments:

Powered by Blogger.