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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章