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<ContainerBuilder>(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
{
/// <summary>
/// Autofac帮助类
/// </summary>
public class IocManager
{
public static IocManager Instance = new IocManager();
public ILifetimeScope Container { get; set; }
public T GetService<T>()
{
return ResolutionExtensions.Resolve<T>((IComponentContext)(object)this.Container);
}
public T GetService<T>(string serviceKey)
{
return ResolutionExtensions.ResolveKeyed<T>((IComponentContext)(object)this.Container, (object)serviceKey);
}
public T GetService<T>(string serviceKey, params Parameter[] parameters)
{
return ResolutionExtensions.ResolveKeyed<T>((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<T>()
{
return ResolutionExtensions.IsRegistered<T>((IComponentContext)(object)this.Container);
}
public bool IsRegistered<T>(string serviceKey)
{
return ResolutionExtensions.IsRegisteredWithKey<T>((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<T>();
|