ASP.NET Core 依赖注入框架的使用(2)

public void ConfigureContainer(ContainerBuilder builder) { //builder.RegisterType<EnglishSayHelloService>().As<ISayHelloService>(); //服务项目程序集 Assembly service = Assembly.Load("Autofac.Service"); //服务接口项目程序集 Assembly iservice = Assembly.Load("Autofac.Service"); builder.RegisterAssemblyTypes(service, iservice).Where(n => n.FullName.EndsWith("Service") && !n.IsAbstract) .InstancePerLifetimeScope().AsImplementedInterfaces(); }

注意: 如果需要注入的服务没有 IXXXService的接口 ,那么 builder.RegisterAssemblyTypes 就只需要传一个程序集。如果服务与接口同在一个项目,那也是要传两个程序集的。

3.接下来在刚刚的控制器中略作修改。

[Route("api/[controller]/[action]")] [ApiController] public class HelloController : ControllerBase { public readonly ISayHelloService sayHelloService; public readonly IUseAutofacService useAutofacService; public HelloController(ISayHelloService _sayHelloService, IUseAutofacService _useAutofacService) { this.sayHelloService = _sayHelloService; this.useAutofacService = _useAutofacService; } [HttpGet] public string AutofacDI() { return sayHelloService.SayHello("AutofacDI"); } public string BathAutofacDI() { var name = sayHelloService.SayHello("AutofacDI"); return useAutofacService.UseAutofac(name); } }

4.用Postman测试注入的情况。

ASP.NET Core 依赖注入框架的使用

到此这篇关于 ASP.NET Core  依赖注入框架的使用的文章就介绍到这了,更多相关 ASP.NET Core  依赖注入框架内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/zwwpgx.html