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

上一篇:vim g的作用


下一篇:VIM记事——大小写转换