博客
关于我
Autofac IOC 依赖注入方式和生命周期以及Autofac配置文件配置IOC属性注入
阅读量:536 次
发布时间:2019-03-09

本文共 4189 字,大约阅读时间需要 13 分钟。

Autofac IOC 依赖注入、生命周期配置及配置文件属性注入

Autofac IOC是一种常用的依赖注入框架,支持多种注入方式和生命周期管理。本文将详细介绍Autofac IOC的依赖注入方式、生命周期配置以及通过配置文件实现的属性注入示例。

第一部分:依赖注入方式

Autofac IOC 提供了多种依赖注入方式,包括:

  • 构造函数注入(默认方式):通过构造函数的参数传递依赖。

  • 属性注入:通过属性的类型或属性修改器注入依赖,适用于接口实现类的属性注入和Controller控制器中的依赖注入。

  • 方法注入:通过方法参数注入依赖,通常用于特殊场景。

  • 接口实现类的属性注入:通过属性注入器注入实现类的依赖。

  • 第二部分:生命周期配置

    Autofac IOC 提供多种生命周期管理选项,主要有:

  • 瞬态(PerDependency):每个依赖都是单独创建的,生命周期与使用处绑定。

  • 单例(SingleInstance):同一个实例被多处使用,适用于资源受限或高频使用的依赖。

  • 作用域(PerLifetimeScope):依赖在相同的作用域内共享实例。

  • 基于标志的作用域(PerMatchingLifetimeScope):“TEST”作用域的依赖实例会在相同标志下重复使用。

  • 请求作用域(PerRequest):依赖在每个请求中重新创建。

  • 第三部分:通过配置文件实现的属性注入

    Autofac允许通过配置文件进行集成。以下是一个典型的配置文件示例:

    {  "components": [    {      "type": "WebAppNet5.TestA, WebAppNet5",      "services": [        {          "type": "WebAppNet5.ITestA, WebAppNet5"        }      ],      "instanceScope": "per-dependency",      "injectProperty": true    },    {      "type": "WebAppNet5.TestB, WebAppNet5",      "services": [        {          "type": "WebAppNet5.ITestB, WebAppNet5"        }      ],      "instanceScope": "single-instance",      "injectProperty": true    },    {      "type": "WebAppNet5.TestC, WebAppNet5",      "services": [        {          "type": "WebAppNet5.ITestC, WebAppNet5"        }      ],      "instanceScope": "per-lifetime-scope",      "injectProperty": true    }  ]}

    接下来是具体的应用示例,展示了如何在代码中实现上述配置。

    第四部分:代码示例

    以下是一个简单的 IOC 测试代码示例:

    public static void TestIOC(){    Console.WriteLine("测试---IOC");    ContainerBuilder builder = new ContainerBuilder();    // 注册TestA并设置为瞬态    builder.RegisterType
    ().As(ITestA>().InstancePerDependency(); // 注册TestB并设置为单例 builder.RegisterType
    ().As(ITestB>().SingleInstance(); // 注册TestC并设置为作用域 builder.RegisterType
    ().As(ITestC>().InstancePerLifetimeScope("TEST"); // 注册TestE并设置为作用域,支持属性注入 builder.RegisterType
    ().As(ITestE>().InstancePerMatchingLifetimeScope("TEST123").PropertiesAutowired(); // 注册Controller并设置为作用域,支持属性注入 builder.RegisterType
    ().As
    ().InstancePerMatchingLifetimeScope("TEST123").PropertiesAutowired()); // 过程初始化 var container = builder.Build(); // 测试单例 var testB = container.Resolve
    (); testB.Show(); // 瞬态测试 var testA = container.Resolve
    (); testA.Show(); var testA1 = container.Resolve
    (); testA1.Show(); Console.WriteLine("瞬态实例是否相同:" + (testA == testA1)); // 作用域测试 using (var scope = container.BeginLifetimeScope("TEST")) { var testE = scope.Resolve
    (); testE.Show(); } Console.WriteLine("测试完成。。。");}

    第五部分:自定义属性选择器

    以下是一个自定义属性选择器的示例,用于控制哪些属性可以注入:

    public class MyPropertySelector : IPropertySelector{    public bool InjectProperty(PropertyInfo propertyInfo, object instance)    {        return propertyInfo.GetCustomAttributes().Any(att => att.GetType() == typeof(CustomPropAttribute));    }}

    第六部分:标记不同的属性

    以下是一个简单的标记特性示例:

    [AttributeUsage(AttributeTargets.Property)]public class CustomPropAttribute : Attribute{}

    第七部分:应用示例

    在实际应用中,可以通过以下步骤实现依赖注入配置:

  • 安装必要的NuGet包:Autofac、Autofac.Configuration、Autofac.Extensions.DependencyInjection。

  • 创建一个Autofac配置文件,例如Config/autofacconfig.json,配置如下:

  • {  "components": [    {      "type": "WebAppNet5.TestA, WebAppNet5",      "services": [        {          "type": "WebAppNet5.ITestA, WebAppNet5"        }      ],      "instanceScope": "per-dependency",      "injectProperty": true    },    {      "type": "WebAppNet5.TestB, WebAppNet5",      "services": [        {          "type": "WebAppNet5.ITestB, WebAppNet5"        }      ],      "instanceScope": "single-instance",      "injectProperty": true    },    {      "type": "WebAppNet5.TestC, WebAppNet5",      "services": [        {          "type": "WebAppNet5.ITestC, WebAppNet5"        }      ],      "instanceScope": "per-lifetime-scope",      "injectProperty": true    }  ]}
    1. 在代码中注册模块和服务,例如:
    2. public void ConfigureServices(IServiceCollection services){    var configurationBuilder = new ConfigurationBuilder();    configurationBuilder.Add(new JsonConfigurationSource() { Path = "Config/autofacconfig.json", Optional = false, ReloadOnChange = true });    var conmodule = new ConfigurationModule(configurationBuilder.Build());    builder.RegisterModule(conmodule);}

      通过以上配置和实例代码,可以在实际应用中灵活管理Autofac IOC的依赖注入行为和生命周期。

    转载地址:http://yjmiz.baihongyu.com/

    你可能感兴趣的文章
    mysqldump备份时忽略某些表
    查看>>
    mysqldump实现数据备份及灾难恢复
    查看>>
    mysqldump数据库备份无法进行操作只能查询 --single-transaction
    查看>>
    mysqldump的一些用法
    查看>>
    mysqli
    查看>>
    MySQLIntegrityConstraintViolationException异常处理
    查看>>
    mysqlreport分析工具详解
    查看>>
    MySQLSyntaxErrorException: Unknown error 1146和SQLSyntaxErrorException: Unknown error 1146
    查看>>
    Mysql_Postgresql中_geometry数据操作_st_astext_GeomFromEWKT函数_在java中转换geometry的16进制数据---PostgreSQL工作笔记007
    查看>>
    mysql_real_connect 参数注意
    查看>>
    mysql_secure_installation初始化数据库报Access denied
    查看>>
    MySQL_西安11月销售昨日未上架的产品_20161212
    查看>>
    Mysql——深入浅出InnoDB底层原理
    查看>>
    MySQL“被动”性能优化汇总
    查看>>
    MySQL、HBase 和 Elasticsearch:特点与区别详解
    查看>>
    MySQL、Redis高频面试题汇总
    查看>>
    MYSQL、SQL Server、Oracle数据库排序空值null问题及其解决办法
    查看>>
    mysql一个字段为空时使用另一个字段排序
    查看>>
    MySQL一个表A中多个字段关联了表B的ID,如何关联查询?
    查看>>
    MYSQL一直显示正在启动
    查看>>