-
在Nuget引入Autofac、Autofac.Extensions.DependencyInjection
-
定义Module,方便对注入服务进行管理
public class AutoFacManager : Autofac.Module { //重写Autofac管道Load方法,在这里注册注入 protected override void Load(ContainerBuilder builder) { //程序集注入业务服务 var IAppServices = Assembly.Load("BaWei.RBAC.Repository"); var AppServices = Assembly.Load("BaWei.RBAC.Service"); //根据名称约定(服务层的接口和实现均以Service结尾),实现服务接口和服务实现的依赖 builder.RegisterAssemblyTypes(IAppServices).Where(t=>t.Name.EndsWith("Repository")).AsImplementedInterfaces(); builder.RegisterAssemblyTypes(AppServices).Where(t=>t.Name.EndsWith("Service")).AsImplementedInterfaces(); } }
-
在Program.cs中注册:
//Autofac注入 builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory()); builder.Host.ConfigureContainer<ContainerBuilder>(builder => { builder.RegisterModule(new AutoFacManager()); });
-
在构造函数中注入:
IService _Service; public RoleController(IService Service) { _Service = Service; }