How to pass parameters at registration time in Autofac
Autofac is a powerful Inversion of Control (IoC) container for .NET applications that simplifies dependency injection (DI), and although it tends to be replaced by the .NET Core out-of-the-box DI, it is still in use in many web applications. You use Autofac to register concrete implementations to interfaces, so that at runtime these implementation are picked without the needing to use the new
keyword.
More complex registrations often require to pass a list of parameters to the constructor of the concrete class. Today we are going to see how to do that.
Modules and the WithParameter method
Modules in Autofac allow you to group related registrations together, making your code more organized and modular. This is particularly useful in large projects where you want to keep your DI configurations clean and maintainable. For example:
public class ExampleModule : Module
{
protected override void Load(ContainerBuilder builder)
{
builder.RegisterType<ConcreteClass>().As<IContract>().WithParameter("parameterName", parameterValue);
}
}
In this example, the ExampleModule
class inherits from the Module
base class, and the Load
method is overridden to register the ConcreteClass
type with a parameter. The WithParameter
method is optional and allows you to specify the parameter name and value that should be passed to the constructor of ConcreteClass
.
and then in the constructor of the ConcreteClass
we would update the code like this:
public class ConcreteClass : IContract
{
private readonly string _parameterValue;
public ConcreteClass(string parameterValue)
{
_parameterValue = parameterValue;
}
// Use the parameterValue in the class
}
Passing Multiple Parameters
You can also pass multiple parameters using the WithParameters
method, which takes an array of NamedParameter objects:
builder.RegisterType<ConcreteClass>().As<IContract>().WithParameters(new[]
{
new NamedParameter("parameterName1", parameterValue1),
new NamedParameter("parameterName2", parameterValue2),
});
It is important to mention that you only need to pass the parameters once during registration, eliminating the need to pass them again when resolving the dependency.
Passing parameters during resolve
If you don’t pass the parameters during registration, you can still provide them during the resolve process. This approach can be useful in scenarios where the parameter values are not known at registration time. The code in this case would look like this:
var concreteClass = scope.Resolve<ConcreteClass>(new NamedParameter("parameterName1", parameterValue1));
Refer to the Autofac documentation for more details on passing parameters during resolve.
Feel free to ask any questions or leave comments below!