项目中引入如下nuget package
<ItemGroup>
<PackageReference Include="Autofac.Extensions.DependencyInjection" Version="7.2.0" />
<PackageReference Include="Microsoft.Extensions.DependencyModel" Version="6.0.0" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.3.0" />
</ItemGroup>
定义三个用于标记的接口,可以自行修改
public interface ISingletonIocTag
{ }
public interface IScopedIocTag
{ }
public interface ITransientIocTag
{ }
简单扩展IOC服务注册
.net 3.x
using System.Linq;
using System.Runtime.Loader;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyModel;
using Microsoft.Extensions.Hosting;
public static class AutofacExtensions
{
public static IHostBuilder UseAutofac(this IHostBuilder host)
{
host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
host.ConfigureContainer<ContainerBuilder>(container =>
{
var libs = DependencyContext.Default.CompileLibraries.Where(lib => lib.Serviceable == false && lib.Type == "project").Select(lib => lib.Name).ToList();
var assemblies = libs.Select(lib => AssemblyLoadContext.Default.LoadFromAssemblyName(new System.Reflection.AssemblyName(lib))).ToArray();
container
.RegisterAssemblyTypes(assemblies)
.Where(type => type.IsAbstract == false && type.IsAssignableTo<ISingletonIocTag>())
.AsSelf()
.AsImplementedInterfaces()
.SingleInstance()
.PropertiesAutowired();
container
.RegisterAssemblyTypes(assemblies)
.Where(type => type.IsAbstract == false && type.IsAssignableTo<IScopedIocTag>())
.AsSelf()
.AsImplementedInterfaces()
.InstancePerLifetimeScope()
.PropertiesAutowired();
container
.RegisterAssemblyTypes(assemblies)
.Where(type => type.IsAbstract == false && type.IsAssignableTo<ITransientIocTag>())
.AsSelf()
.AsImplementedInterfaces()
.InstancePerDependency()
.PropertiesAutowired();
container
.RegisterAssemblyTypes(assemblies)
.Where(type => type.IsAbstract == false && type.IsAssignableTo<ControllerBase>())
.AsSelf()
.InstancePerDependency()
.PropertiesAutowired();
});
return host;
}
}
dotnet 5.x、6.x
using System.Linq;
using System.Runtime.Loader;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyModel;
using Microsoft.Extensions.Hosting;
public static class AutofacExtensions
{
public static IHostBuilder UseAutofac(this IHostBuilder host)
{
host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
host.ConfigureContainer<ContainerBuilder>(container =>
{
var libs = DependencyContext.Default.CompileLibraries.Where(lib => lib.Serviceable == false && lib.Type == "project").Select(lib => lib.Name).ToList();
var assemblies = libs.Select(lib => AssemblyLoadContext.Default.LoadFromAssemblyName(new System.Reflection.AssemblyName(lib))).ToArray();
container
.RegisterAssemblyTypes(assemblies)
.Where(type => type.IsAbstract == false && type.IsAssignableTo(typeof(ISingletonIocTag)))
.AsSelf()
.AsImplementedInterfaces()
.SingleInstance()
.PropertiesAutowired();
container
.RegisterAssemblyTypes(assemblies)
.Where(type => type.IsAbstract == false && type.IsAssignableTo(typeof(IScopedIocTag)))
.AsSelf()
.AsImplementedInterfaces()
.InstancePerLifetimeScope()
.PropertiesAutowired();
container
.RegisterAssemblyTypes(assemblies)
.Where(type => type.IsAbstract == false && type.IsAssignableTo(typeof(ITransientIocTag)))
.AsSelf()
.AsImplementedInterfaces()
.InstancePerDependency()
.PropertiesAutowired();
container
.RegisterAssemblyTypes(assemblies)
.Where(type => type.IsAbstract == false && type.IsAssignableTo(typeof(ControllerBase)))
.AsSelf()
.InstancePerDependency()
.PropertiesAutowired();
});
return host;
}
}
替换IOC容器
dotnet 3.x、5.x
public class Program
{
public static void Main(string[] args)
{
CreateHostBuilder(args).Build().Run();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
}).UseAutofac();
}
---
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers().AddControllersAsServices();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "Dotnet3WebApiDemo", Version = "v1" });
});
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "Dotnet3WebApiDemo v1"));
}
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
}
dotnet 6.x
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers().AddControllersAsServices();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Host.UseAutofac();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthorization();
app.MapControllers();
app.Run();
网友评论