ASP.Net.Mvc
引用
代码语言:javascript复制install-package autofac
install-package Mvc5
代码语言:javascript复制//创建一个用于注册的对象
ContainerBuilder builder = new ContainerBuilder()
//获取实现类的程序集
Assembly[] assembly = new Assembly[]{Assembly.Load(实现类程序集)}
builder.RegisterAssemblyTypes(assembly) //注册程序集
.Where(y=>!y.IsAbstract)//不是抽象类
.AsImplementedInterfaces()//注册所有实现接口
.PropertiesAutowired(); //自动注入 (必须为属性)
//将本程序所有控制器全部注册
builder.RegisterControllers(typeof(MvcApplication).Assembly)
.PropertiesAutowired();
Container container = builder.Build();
//将当前容器的控制器工厂替换掉默认的控制器工厂,(即:不要MVC默认的控制器工厂,用autofac容器中的控制器替代)
//DefaultControllerFactory mvc默认的控制器工厂
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
代码填入Global中
Asp.Net.Core
引用
代码语言:javascript复制install-package autofac
install-package autofac-extensions.DependencyInjection
代码,添加到Startup的服务中
代码语言:javascript复制public IServiceProvider ConfigureServices(IServiceCollection service)
{
service.AddMvc();
var builder = new ContainerBuilder();
Assembly[] assembly = new Assembly[] { Assembly.Load("AutoFacDemo.BLL") };
builder.RegisterAssemblyTypes(assembly)
.AsImplementedInterfaces()
.PropertiesAutowired();
builder.Populate(service);
return new AutofacServiceProvider(builder.Build());
}