封装AutoFac
using Autofac;
using System.Reflection;
namespace WebApplication1
{
public class AutoFacModel: Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
Assembly repository = Assembly.Load("Repository");
builder.RegisterAssemblyTypes(repository)
.Where(type => type.Name.EndsWith("Repository"))
.AsImplementedInterfaces()
.InstancePerLifetimeScope();
Assembly service = Assembly.Load("Service");
builder.RegisterAssemblyTypes(service)
.Where(type => type.Name.EndsWith("Service"))
.AsImplementedInterfaces()
.InstancePerLifetimeScope();
}
}
}
WebapplicationBuilder扩展方法
using Autofac;
using Autofac.Extensions.DependencyInjection;
namespace WebApplication1
{
public static class ExceptionApplicationbuilder
{
public static void InitFac(this WebApplicationBuilder builder)
{
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
{
builder.RegisterModule<AutoFacModel>();
});
}
}
}
program注入
Builder.InitFac();