Program.cs 配置:
using Autofac; using Autofac.Extensions.DependencyInjection; using System.Reflection; using WebApplication3; var builder = WebApplication.CreateBuilder(args); // 1.将默认ServiceProviderFactory指定为AutofacServiceProviderFactory builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()); builder.Host.ConfigureContainer(builder => { // 2.自动注册 Assembly assembly = Assembly.Load("Jasper.Application.Base"); builder.RegisterAssemblyTypes(assembly).AsImplementedInterfaces().InstancePerDependency(); }); // 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(); // 3.获取Autofac注入的实例 IocManager.Instance.Container = app.UseHostFiltering().ApplicationServices.GetAutofacRoot(); // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); } app.UseAuthorization(); app.MapControllers(); app.Run();
Autofac帮助类:
using Autofac;
using Autofac.Core;
namespace WebApplication3
{
///
/// Autofac帮助类
///
public class IocManager
{
public static IocManager Instance = new IocManager();
public ILifetimeScope Container { get; set; }
public T GetService()
{
return ResolutionExtensions.Resolve((IComponentContext)(object)this.Container);
}
public T GetService(string serviceKey)
{
return ResolutionExtensions.ResolveKeyed((IComponentContext)(object)this.Container, (object)serviceKey);
}
public T GetService(string serviceKey, params Parameter[] parameters)
{
return ResolutionExtensions.ResolveKeyed((IComponentContext)(object)this.Container, (object)serviceKey, parameters);
}
public object GetService(Type serviceType)
{
return ResolutionExtensions.Resolve((IComponentContext)(object)this.Container, serviceType);
}
public object GetService(string serviceKey, Type serviceType)
{
return ResolutionExtensions.ResolveKeyed((IComponentContext)(object)this.Container, (object)serviceKey, serviceType);
}
public bool IsRegistered()
{
return ResolutionExtensions.IsRegistered((IComponentContext)(object)this.Container);
}
public bool IsRegistered(string serviceKey)
{
return ResolutionExtensions.IsRegisteredWithKey((IComponentContext)(object)this.Container, (object)serviceKey);
}
public bool IsRegistered(Type serviceType)
{
return ResolutionExtensions.IsRegistered((IComponentContext)(object)this.Container, serviceType);
}
public bool IsRegisteredWithKey(string serviceKey, Type serviceType)
{
return ResolutionExtensions.IsRegisteredWithKey((IComponentContext)(object)this.Container, (object)serviceKey, serviceType);
}
}
}
使用:
var testIoc = IocManager.Instance.GetService();



