使用新的单文件模板将 Autofac 添加到 .NET core 6.0

git*_*202 42 c# autofac asp.net-core-6.0

我正在尝试将 Autofac 添加到 .Net 6.0 Web API。我使用最新的 ASP.NET Core Web API 模板来生成单个启动 Program.cs 文件。

安装的 Autofac 版本:

Autofac 6.3.0
Autofac.Extensions.DependancyInjection (7.2.0-preview.1)
Run Code Online (Sandbox Code Playgroud)

安装的.Net 6.0版本:

Microsoft.AspNetCore.App 6.0.0-rc.2.21480.10
Microsoft.NETCore.App 6.0.0-rc.2.21480.5
Microsoft.WindowsDesktop.App 6.0.0-rc.2.21501.6
Run Code Online (Sandbox Code Playgroud)

以防万一,这是 Program.cs 文件的全部内容(是的,没有命名空间或类定义。​​只有 Program.cs 文件,没有 StartUp 类或 Startup.cs 文件)

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run()
Run Code Online (Sandbox Code Playgroud)

我尝试查看最新的 Autofac 文档,但其中的示例尽管针对 .Net Core 3.x 及更高版本,但似乎不适合 .Net 6.0 代码。我不知道如何将 Autofac 添加到中间件管道中。

任何帮助是极大的赞赏。

Autofac 网站的代码片段

public class Program
{
  public static void Main(string[] args)
  {
    // ASP.NET Core 3.0+:
    // The UseServiceProviderFactory call attaches the
    // Autofac provider to the generic hosting mechanism.
    var host = Host.CreateDefaultBuilder(args)
        .UseServiceProviderFactory(new AutofacServiceProviderFactory())
        .ConfigureWebHostDefaults(webHostBuilder => {
          webHostBuilder
            .UseContentRoot(Directory.GetCurrentDirectory())
            .UseIISIntegration()
            .UseStartup<Startup>();
        })
        .Build();

    host.Run();
  }
}
Run Code Online (Sandbox Code Playgroud)

Autofac 文档:

https://docs.autofac.org/en/latest/integration/aspnetcore.html#asp-net-core-3-0-and-generic-hosting

小智 64

我找到了这个微软文档

var builder = WebApplication.CreateBuilder(args);

builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());

// Register services directly with Autofac here.
// Don't call builder.Populate(), that happens in AutofacServiceProviderFactory.
builder.Host.ConfigureContainer<ContainerBuilder>(
   builder => builder.RegisterModule(new MyApplicationModule()));

var app = builder.Build();
Run Code Online (Sandbox Code Playgroud)

  • 对于像我这样的复制粘贴者:您还需要添加 Autofac.Extensions.DependencyInjection 包,而不仅仅是 Autofac。 (10认同)
  • ConfigureContainer 是通用的,应该引用 AutoFac ContainerBuilder 类型,如下所示: builder.Host.ConfigureContainer&lt;ContainerBuilder&gt;(containerBuilder =&gt; { containerBuilder.RegisterModule(new EmptyModule()); }); (2认同)

小智 22

在“Program.cs”中

你会找到

var builder = WebApplication.CreateBuilder(args);
Run Code Online (Sandbox Code Playgroud)

添加如下

builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory())
    .ConfigureContainer<ContainerBuilder>(builder =>
    {
        builder.RegisterModule(new AutofacBusinessModule());
    });
Run Code Online (Sandbox Code Playgroud)

上面的答案,我假设您已经设置好其他所有内容。我正在使用 Autofac 和 Autofact.Extras.DynamicProxy

下面分享我的 AutofacBusinessModule 只是为了澄清。

public class AutofacBusinessModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterType<ProductManager>().As<IProductService>().SingleInstance();
            builder.RegisterType<EfProductDal>().As<IProductDal>().SingleInstance();
        }
    }
Run Code Online (Sandbox Code Playgroud)


Oba*_*san 11

我附上了手动声明和反射 API 的示例,说明如何添加Autofac.NET Core 6.0

  1. 调用UseServiceProviderFactoryHost 子属性
  2. 调用ConfigureContainerHost 子属性
  3. 声明您的服务及其生命周期

手动服务声明示例

var builder = WebApplication.CreateBuilder(args);

// Call UseServiceProviderFactory on the Host sub property 
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());

// Call ConfigureContainer on the Host sub property 
builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
{
   // Declare your services with proper lifetime

    builder.RegisterType<AppLogger>().As<IAppLogger>().SingleInstance();
    builder.RegisterType<DataAccess>().As<IDataAccess>().InstancePerLifetimeScope();

});

Run Code Online (Sandbox Code Playgroud)

程序集扫描“Reflection API”示例

var builder = WebApplication.CreateBuilder(args);

// Call UseServiceProviderFactory on the Host sub property 
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());

// Call ConfigureContainer on the Host sub property 
builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
{
 builder.RegisterAssemblyTypes(Assembly.Load(nameof(DemoLibrary))).Where(t => t.Namespace?.Contains("Practicing.Services") == true)
    .As(t => t.GetInterfaces().FirstOrDefault(i => i.Name == "I" + t.Name));

});
Run Code Online (Sandbox Code Playgroud)