Using AutoFac On ASP.Net 5 (A Thirdparty Inversion of Control Container)



Published On Wednesday April 21, 2021 Reading Time: 3 minutes

.Net Core does ships with a built-in dependency injection framework. But there is a certain limitation with it so most of the developers prefer a third-party dependency framework. Though the default DI may offer enough functionality, as the system grows you might need some extra features. Some like resolving a service with some associated metadata, named variant of a service, lazy instantiation, and much more. So, a third-party DI framework comes to the rescue on these. So, here we will be able to instantiate a third party DI framework, which will be Autofac, it is one of the plenty DI framework present today.

Here I am going through a .Net 5 Web API Application Default Template.

To start with the implementation you will need to install Two Nuget packages

  1. Autofac
    Until this post the version is maintained at 6.1.0
  2. Autofac.Extensions.DependencyInjection
    Until this post the version is maintained at 7.1.0

Now for demonstration let us create one interface and and one class that implements it for resolving the dependency name ITestDate and TestData as below

ITestData.cs

/// <summary>
/// Test Interface
/// </summary>
public interface ITestData
{
    /// <summary>
    /// Returns Simple Text
    /// </summary>
    /// <returns></returns>
    string TestString();
}

TestData.cs

/// <summary>
/// Test Class
/// </summary>
public class TestData : ITestData
{
    /// <summary>
    /// Returns Simple Text
    /// </summary>
    /// <returns></returns>
    public string TestString()
    {
        return "hello";
    }
}

 

Step 1 : For registering Autofac service on the ConfigureServices method on the Startup.cs file
/// <summary>
/// This method gets called by the runtime. Use this method to add services to the container.
/// </summary>
/// <param name="services"></param>
public void ConfigureServices(IServiceCollection services)
{
    services.AddControllers();
    services.AddAutofac();
}
Step 2 : Now that you have added the code in the method you need to add a method on the Startup.cs file as
/// <summary>
/// Configure Container
/// </summary>
/// <param name="builder"></param>
public void ConfigureContainer(ContainerBuilder builder)
{
       //Here you add the dependency  
}
Step 3 : Now you have added the method ConfigureContainer now with reference with the above example of an interface and class we add the code as:
/// <summary>
/// Configure Container
/// </summary>
/// <param name="builder"></param>
public void ConfigureContainer(ContainerBuilder builder)
{
    builder.RegisterType<TestData>().As<ITestData>();
}

And now you are done with adding Autofac as the third party DI framework on your application.

Now for injecting the dependency on your application its as usual the same code that we use using the default DI

/// <summary>
/// Weather Forecast Controller
/// </summary>
[ApiController]
[Route("api/[controller]")]
public class WeatherForecastController : ControllerBase
{
    private readonly ITestData _testData;
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };
    /// <summary>
    /// Constructor
    /// </summary>
    public WeatherForecastController(ITestData testData)
    {
        _testData = testData;
    }
 }

Now you can simple use the method as:

/// <summary>
/// Get Weather Data
/// </summary>
/// <returns></returns>
[HttpGet]
[Route("Weather")]
public IEnumerable<WeatherForecast> GetWeatherV1()
{
    var helloString = _testData.TestString();
    var rng = new Random();
    return Enumerable.Range(1, 5).Select(index => new WeatherForecast
    {
        Date = DateTime.Now.AddDays(index),
        TemperatureC = rng.Next(-20, 55),
        Summary = Summaries[rng.Next(Summaries.Length)]
    })
    .ToArray();
}

So this is how we can start to use Autofac as the third party DI framework in our application.

Extras:

Generally there can be whole lot of dependency within the application so this can make our Startup.cs class very lengthy and dirty so we can have cleaner code by adding another class and using it to insert the dependency.

Step 1: Lets create a class name AutoFacDependencyInjectionExtension.cs (this is where we add all the dependency from now) and add the content as :
    /// <summary>
    /// Register Dependency Injection
    /// </summary>
    public static class AutoFacDependencyInjectionExtension
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        public static ContainerBuilder RegisterDependencyInjection(this ContainerBuilder builder)
        {
            builder.RegisterType<TestData>().As<ITestData>();
            return builder;
        }
    }
Step 2: Modify the ConfigureContainer method as
/// <summary>
/// Configure Container
/// </summary>
/// <param name="builder"></param>
public void ConfigureContainer(ContainerBuilder builder)
{
    builder.RegisterDependencyInjection();
}

So, now our Startup.cs class will look cleaner. 🙂

So, this is the really basic guide to how to start using Autofac as the replacement of the built in DI framework.

Did you find this blog post helpful I hope it does? whom could you share it with for more reach?

🙂

 

 

0 0 votes
Article Rating
Subscribe
Notify of
guest
2 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Jason B
Jason B
3 years ago

I tried this example and landed on this error in Program.cs

Unable to cast object of type ‘Microsoft.Extensions.DependencyInjection.ServiceCollection’ to type ‘Autofac.ContainerBuilder’.’

Is this code up to date?

2
0
Would love your thoughts, please comment.x
()
x