SoFunction
Updated on 2025-04-08

Project Practice Using Autofac in Core 6.0

1. Quote the NuGet package

Install-Package Autofac -Version 6.3.0
Install-Package  -Version 7.2.0

2. Register and use in Program

2.1 Normal injection

(new AutofacServiceProviderFactory());
<ContainerBuilder>(builder => {
    <A>().As<IA>();  // Register a certain class and interface directly. The one on the left is the implementation class and the As on the right is the interface});

2.2 Reflection assembly method service registration

<ContainerBuilder>(builder =>
{
   var assemblysServices = ("");
   (assemblysServices)
              .AsImplementedInterfaces()
              .InstancePerLifetimeScope();
});

Selective batch injection can also be performed, and after injection, it is used by constructor or property injection.

3. Description of common methods in AutoFac

Basic concepts

1. AsImplementedInterfaces() is injected in an interface manner, injecting all public interfaces of these classes as services.

2. InstancePerRequest() Share the same instance every time you request it, and when using ef, different operations use the same data context.

3. PreserveExistingDefaults() If more than one component exposes the same service,Autofac will use the last registered component as the provider of the service.Then use PreserveExistingDefaults to prevent the subsequent registration from overwriting the previous registration

&lt;A&gt;() .As&lt;IA&gt;();

&lt;AA&gt;() .As&lt;IA&gt;();  // This way AA will cover A
&lt;AA&gt;() .As&lt;IA&gt;().PreserveExistingDefaults(); // In this way, A is the default value of IA and will not be overwritten by AA

4. InstancePerDependency creates a new object, a unique instance for each dependency or call (Resolve()).

5. SingleInstance uses the same object and singleton pattern for each request. Tells the container that it is a singleton, but this singleton does not need to be implemented by itself.

6. RegisterGeneric Register generic class

(typeof(Repository<>)).As(typeof(IRepository<>))

7. RegisterInstance() registers an instance, for example: registers an instance of an existing object, so that the instance can be converted into an instance hosted by the container.

8. RegisterControllers() Register Controllers

(()); // Register all Controllers in the current assembly

9. RegisterFilterProvider() Register Filter filter

()

10. RegisterAssemblyTypes Register Class

(()); // Register all classes in the current assembly

11. InstancePerMatchingLifetimeScope In an identified lifecycle field, each dependency or call creates a single shared instance. Instances in parent domains can be shared in the child domain in the identified life cycle domain.

<A>() .AsImplementedInterfaces() .InstancePerMatchingLifetimeScope();

12. InstancePerHttpRequest shares a component instance in the context of an Http request. Applicable to mvc development only

13. InstancePerLifetimeScope In a life cycle, each dependency component or call (Resolve()) creates a single shared instance, and for each different life cycle domain, the instance is different.

14. UsingConstructor (parameter) Automatic assembly, manually use specific constructors

&lt;A&gt;().UsingConstructor(typeof(IA),typeof(IAA)); // This specifies that the constructor of A (IA, IAA) is called. If the constructor does not exist, an error will be reported.

15. [AsClosedTypesOf(open)]AsClosedTypesOf(typeof(IA<>)): If it is multiple inheritance, the service (interface) corresponding to the registered assembly is the open generic instance (interface) closest to this class

(A).AsClosedTypesOf(typeof(IRepository<>));

Lifecycle involved in Autofac

//1. Instant life cycle: After registration, the service instance obtained each time is different (the default registration method)&lt;UserService&gt;().As&lt;IUserService&gt;().InstancePerDependency();
//2. Singleton life cycle: The service instances obtained in the entire container are the same&lt;UserService&gt;().As&lt;IUserService&gt;().SingleInstance();
//3. Scope life cycle: The service instances obtained under the same scope are the same&lt;UserService&gt;().As&lt;IUserService&gt;().InstancePerLifetimeScope();
//4. Scope life cycle: You can specify a scope and then share a service instance under the same scope&lt;UserService&gt;().As&lt;IUserService&gt;().InstancePerMatchingLifetimeScope("My");
//5. The life cycle of the http request context: in an Http request context, share a component instance.  Applicable to mvc development only.&lt;UserService&gt;().As&lt;IUserService&gt;().InstancePerRequest();
//6. Create a new nested life cycle scope with implicit relationship types. In the life cycle of the instances owned in a life cycle domain,// Each dependent component or call the Resolve() method to create a single shared instance, and the child lifecycle domain shares the instance in the parent lifecycle domain&lt;UserService&gt;().InstancePerOwned&lt;IUserService&gt;(); 

This is the end of this article about the project practice of using Autofac in Core 6.0. For more related content on Core using Autofac, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!