Autofac自动注入是通过名称约定来实现依赖注入
ps:本demo接口层都以“I”开头,以“Service”结尾。服务层实现都以“Service”结尾。
为什么要实现自动注入
大多时候,我们都是 以下方式进行依赖注入
public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); //初始化容器 var builder = new ContainerBuilder(); //管道寄居 builder.Populate(services); builder.RegisterType<TestService>().As<ITestService>();//UserService注入到IUserService //构造 ApplicationContainer = builder.Build(); //将AutoFac反馈到管道中 return new AutofacServiceProvider(ApplicationContainer); }
随着业务的增长,接口跟实现类会越来越多,还需要手动一个个的注册依赖项,有时候会出现忘了写配置,导致程序报错,如果是多人开发,可能还会导致代码冲突,后期维护起来相对来说比较麻烦。
实用Autofac自动注入
public IServiceProvider ConfigureServices(IServiceCollection services) { services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2); //初始化容器 var builder = new ContainerBuilder(); //管道寄居 builder.Populate(services); //业务逻辑层所在程序集命名空间 Assembly service = Assembly.Load("NetCoreDemo.Service"); //接口层所在程序集命名空间 Assembly repository = Assembly.Load("NetCoreDemo.Repository"); //自动注入 builder.RegisterAssemblyTypes(service, repository) .Where(t => t.Name.EndsWith("Service")) .AsImplementedInterfaces(); //构造 ApplicationContainer = builder.Build(); //将AutoFac反馈到管道中 return new AutofacServiceProvider(ApplicationContainer); }
简单测试
创建IUserService接口
public interface ITestService { string Hello(); }
创建UserService实现类
public class TestService : ITestService { public string Hello() { return "Hello Word"; } }
创建TestController控制器
通过控制器的构造方法注入ITestService接口
[Route("api/test")] [ApiController] public class TestController : Controller { private readonly ITestService _testService; /// <summary> /// 构造函数 /// </summary> /// <param name="testService"></param> public TestController(ITestService testService) { _testService = testService; } [HttpGet] public string Hello() { var str= _testService.Hello(); return str; } }
运行
来源:https://www.cnblogs.com/netcs/p/12194893.html