.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
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"; } }
/// <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(); }
/// <summary> /// Configure Container /// </summary> /// <param name="builder"></param> public void ConfigureContainer(ContainerBuilder builder) { //Here you add the dependency }
/// <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.
/// <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; } }
/// <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?
🙂
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?
Dear Json,
Can you please share your code in Program.cs file