Autofac
Posted jinweichang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Autofac相关的知识,希望对你有一定的参考价值。
安装配置
1.NuGet安装Autofac.Extensions.DependencyInjection
2.在Program中添加.UseServiceProviderFactory(new AutofacServiceProviderFactory())这句。
public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .UseServiceProviderFactory(new AutofacServiceProviderFactory()) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); }
在Startup中添加方法ConfigureContainer,在此方法中直接注册组件。
public void ConfigureContainer(ContainerBuilder builder) { var basePath = AppContext.BaseDirectory; // Register your own things directly with Autofac, like: //builder.RegisterModule(new autofac3()); var dllpath = Path.Combine(basePath, "Service.dll"); var assemblysdllpath = Assembly.LoadFrom(dllpath); builder.RegisterAssemblyTypes(assemblysdllpath).AsImplementedInterfaces(); }
应用
[Route("api/[controller]/[action]")] [ApiController] public class StudentController : ControllerBase { protected readonly IGetStu _gg; public StudentController(IGetStu gg) { _gg = gg; } [HttpPost] public ActionResult<string> getname(string name) { return _gg.getname("jinwei"); } }
参考资料:https://autofac.readthedocs.io/en/latest/integration/aspnetcore.html
以上是关于Autofac的主要内容,如果未能解决你的问题,请参考以下文章