Install-Package Autofac
Install-Package Autofac.Extensions.DependencyInjection
创建.NET 6控制台应用程序并打开Program.cs
导入以下命名空间:
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
CreateHostBuilder
方法,以使用Autofac替换默认的ServiceCollection:public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureContainer(builder => {
// 注册依赖项
})
.ConfigureServices((hostContext, services) =>
{
// 添加服务到ServiceCollection
});
ConfigureContainer
方法中,注册类和它们的接口或基类作为接口的实现:public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory())
.ConfigureContainer(builder => {
// 将实现IService接口的类注册到容器
builder.RegisterType().As();
})
.ConfigureServices((hostContext, services) =>
{
// 添加服务到ServiceCollection
});
class Program
{
private readonly IService _service;
// 通过构造函数注入IService实例
public Program(IService service)
{
_service = service;
}
static void Main(string[] args)
{
// 创建宿主,启动应用程序
var builder = CreateHostBuilder(args);
using var host = builder.Build();
using var scope = host.Services.CreateScope();
// 获取注册为IService类型的实例
var service = scope.ServiceProvider.GetRequiredService();
service.Run();
Console.ReadLine();
}
}