【Autofac】 学习笔记

 

1、引入nuget包

【Autofac】 学习笔记

 

 2、修改Program.cs

public static void Main(string[] args)
 {
      Host.CreateDefaultBuilder(args)
          .UseServiceProviderFactory(new AutofacServiceProviderFactory())
          .ConfigureWebHostDefaults(webBuilder =>
           {
                  webBuilder
                      .UseContentRoot(Directory.GetCurrentDirectory())
                      .UseUrls("http://*:2020")
                      .UseStartup<Startup>();
          });
}

3、修改Startup.cs

增加一个ConfigureContainer方法

【Autofac】 学习笔记

 

 

 代码如下:

public void ConfigureContainer(ContainerBuilder builder)
 {
    builder.RegisterModule<AutofacModuleRegister>();var controllerBaseType = typeof(ControllerBase);
    builder.RegisterAssemblyTypes(typeof(Program).Assembly)
           .Where(t => controllerBaseType.IsAssignableFrom(t) && t != controllerBaseType)
           .PropertiesAutowired();
 }

 

 这里我用的是程序集注入,新建一个AutofacModuleRegister类

【Autofac】 学习笔记

 

 

代码如下:

public class AutofacModuleRegister : Autofac.Module
    {
        private static readonly ILog log = LogManager.GetLogger(typeof(AutofacModuleRegister));
        protected override void Load(ContainerBuilder builder) 
        {
            var basePath = AppContext.BaseDirectory;

            var serviceDllFile = Path.Combine(basePath, "*.Service.dll");//*号是项目名称前缀

            if (!File.Exists(serviceDllFile))
            {
                var msg = "service.dll 丢失。";
                log.Error(msg);
                throw new Exception(msg);
            }
            var cacheType = new List<Type>();
            // 获取 Service.dll 程序集服务,并注册
            var assemblysServices = Assembly.LoadFrom(serviceDllFile);
            builder.RegisterAssemblyTypes(assemblysServices)
                      .AsImplementedInterfaces()
                      .InstancePerDependency()//用于控制对象的生命周期,每次加载实例时都是新建一个实例,默认就是这种方式。调用的话
                      .PropertiesAutowired()
                      .EnableInterfaceInterceptors()//引用Autofac.Extras.DynamicProxy;
                      .InterceptedBy(cacheType.ToArray());//允许将拦截器服务的列表分配给注册。
        }
    }

 

上一篇:Springboot 整和/集成 ElasticSearch


下一篇:es启动报错解决 maybe these locations are not writable or multiple nodes were started without increasing