标签:pat assembly vat str services 开发 容器 res 业务逻辑
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); }
随着业务的增长,接口跟实现类会越来越多,还需要手动一个个的注册依赖项,有时候会出现忘了写配置,导致程序报错,如果是多人开发,可能还会导致代码冲突,后期维护起来相对来说比较麻烦。
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); }
public interface ITestService { string Hello(); }
public class TestService : ITestService { public string Hello() { return "Hello Word"; } }
通过控制器的构造方法注入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; } }
运行
标签:pat assembly vat str services 开发 容器 res 业务逻辑
原文地址:https://www.cnblogs.com/tenghao510/p/11959322.html