赛派号

固态电池车上市时间表 How to pass parameters at registration time in Autofac

CSharp 18 Mar 2025 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().As().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().As().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鈥檛 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(new NamedParameter("parameterName1", parameterValue1));

Refer to the Autofac documentation for more details on passing parameters during resolve.

Feel free to ask any questions or lee comments below!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至lsinopec@gmail.com举报,一经查实,本站将立刻删除。

上一篇 没有了

下一篇没有了