Official Documentation
https://autofaccn.readthedocs.io/zh/latest/index.html
Creating a .NET Core Console Application
Registering Types – Example One
-
Define an interface
IPersonpublic interface IPerson { void Introduce(); } -
Implemant the interface with a
Workerclasspublic class Worker : IPerson { public void Introduce() { Console.WriteLine("I am a worker"); } } -
Create a registration class and configure the container
public class BasicRegistrations { /// <summary> /// Register and resolve by type /// </summary> public static void ExecuteTypeRegistration() { var builder = new ContainerBuilder(); builder.RegisterType<Worker>().As<IPerson>(); var container = builder.Build(); var provider = new AutofacServiceProvider(container); var person = provider.GetService<IPerson>(); person.Introduce(); Console.ReadKey(); } } -
Run the application
class Program { static void Main(string[] args) { Console.WriteLine("autofac demo"); BasicRegistrations.ExecuteTypeRegistration(); } }Output:

Assembly Scanning for Automatic Registration
Registering dozens of components manually is impractical. Assembly scanning allows automatic discovery and registration.
Example Two
-
Define a marker interface for atuomatic injection
/// <summary> /// Implementing this interface enables automatic dependency registration /// </summary> public interface IAutoRegister { } -
Create the scanning logic in a dedicated class
public class AssemblyScanner { /// <summary> /// Build a service provider by scanning assemblies /// </summary> public AutofacServiceProvider Build() { var builder = new ContainerBuilder(); Type markerType = typeof(IAutoRegister); var assemblies = AppDomain.CurrentDomain.GetAssemblies().ToArray(); builder.RegisterAssemblyTypes(assemblies) .Where(t => markerType.IsAssignableFrom(t) && !t.IsAbstract) .AsImplementedInterfaces() .InstancePerLifetimeScope(); var container = builder.Build(); return new AutofacServiceProvider(container); } } -
Implement both
IPersonandIAutoRegisterin aTeacherclassclass Teacher : IPerson, IAutoRegister { public void Introduce() { Console.WriteLine("I am a teacher"); } } -
Udpate the entry point to use the scanner
static void Main(string[] args) { Console.WriteLine("autofac demo"); BasicRegistrations.ExecuteAssemblyScan(); }Output:

References
https://stackoverflow.com/questions/26957519/ef-core-mapping-entitytypeconfiguration