码迷,mamicode.com
首页 > Web开发 > 详细

.Net Core + Autofac

时间:2021-06-25 17:09:08      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:class   png   startup   packages   image   sem   interface   change   source   

Enviroment:

.Net(5.0)

Autofac(6.2.0)

Autofac.Configuration(6.0.0)

Autofac.Extensions.DependencyInjection(7.1.0)

1. first intall follow packages

技术图片

 2. use autofac in ‘Program.cs‘ file to replace original IOC of .net core

技术图片

 3. add ConfigureContainer methord  in startup,

技术图片

 4. add autofac.json file  

{
  "defaultAssembly": "AutofacService",
  "components": [
    {
      "type": "AutofacService.RemoteLogger, AutofacService",
      "services": [
        {
          "type": "AutofacIService.ISimpleLogger,AutofacIService"
        }
      ],
      "injectProperties": true
    }
  ]
}

5. register configuration module in startup 

    public void ConfigureContainer(ContainerBuilder builder)
        {
            //builder.RegisterType<SimpleLogger>().As<ISimpleLogger>().InstancePerLifetimeScope();
            ////register a generic type like Respository<>
            //builder.RegisterGeneric(typeof(DatabaseExtension<>)).As(typeof(IDatabaseExtension<>)).InstancePerLifetimeScope();

            //var assemblyIService = Assembly.Load("autofac_demo.IService");
            //var assemblyService = Assembly.Load("autofac_demo.Service");
            //builder.RegisterAssemblyTypes(assemblyIService, assemblyService).Where(t => t.Name.EndsWith("Service")).AsImplementedInterfaces();

            //load config json
            var config = new ConfigurationBuilder().Add(new JsonConfigurationSource()
            {

                Path = "Config/autofac.json",
                Optional = false,
                ReloadOnChange = true
            });

            builder.RegisterModule(new ConfigurationModule(config.Build()));
            //builder.Build();

        }

6. test successful

技术图片

 

.Net Core + Autofac

标签:class   png   startup   packages   image   sem   interface   change   source   

原文地址:https://www.cnblogs.com/kevin-xk/p/14930144.html

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