Fixing Property Injection with Autofac in ASP.NET Core
- Backend
- 16 Jun, 2024
When using Autofac for dependency injection in my ASP.NET Core project, I encountered a NullReferenceException
when I tried to implement property injection.
After some investigation, I found the issue was caused by the controller activator not being configured correctly. Here’s a simplified explanation:
Problem Analysis
- Default Controller Activator: By default, ASP.NET Core uses
DefaultControllerActivator
, which only supports constructor injection. If the controllers rely on property injection, this activator won’t handle those properties, resulting in null dependencies. - Autofac Integration: Autofac can handle complex dependency injection scenarios, including property injection, but this requires using the correct controller activator.
Solution
To enable Autofac to manage property injection, we need to use ServiceBasedControllerActivator
. This is why adding the following line in Program.cs
fixes the issue:
builder.Services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>());
This line tells ASP.NET Core to use ServiceBasedControllerActivator
, which will resolve controllers and their dependencies from the DI container, including property injections.