码迷,mamicode.com
首页 > 其他好文 > 详细

Autofac

时间:2020-03-30 13:18:05      阅读:80      评论:0      收藏:0      [点我收藏+]

标签:ado   ocs   acs   tps   contain   factor   gets   ted   with   

 

 

安装配置

 

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

标签:ado   ocs   acs   tps   contain   factor   gets   ted   with   

原文地址:https://www.cnblogs.com/JinweiChang/p/12597616.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!