Autofac 3种常见注入IOC 以及生命周期 以及Net6 简单注入

 

 .Net6 简单使用构造函数注入

using System.Reflection;
using Autofac;
using Autofac.Extensions.DependencyInjection; //直接引入该Nuget package即可
using mywebapi.service.Application;
using mywebapi.service.Application.Contracts;
using System.Linq;

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();
//AutofacServiceProviderFactory
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()).ConfigureContainer<ContainerBuilder>(c =>
{
    //注入单个
    // c.RegisterType<TestService>().AsImplementedInterfaces();
    //注入单个
    // c.RegisterType<TestService>().As<ITestService>();

    //批量注入
    Assembly assembly = Assembly.Load("mywebapi.service.Application");
    c.RegisterAssemblyTypes(assembly).AsImplementedInterfaces();
});



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();

 

posted @ 2023-07-17 15:23  天天向上518  阅读(35)  评论(0编辑  收藏  举报