基于autofac的属性注入

什么是属性注入

在了解属性注入之前,要先了解一下DI(Dependency Injection),即依赖注入。在ASP.NET Core里自带了一个IOC容器,而且程序支行也是基于这个容器建立起来的,在 Startup 里的 ConfigureService 方法里向容器注册服务类型。

简单来说,依赖注入就是容器帮我们“new”一个对象,并且管理对象的生命周期。

在依赖注入时,最常用的是构造方法注入。还有另一种方法,那就是属性注入

在ASP.NET Core中,自带的容器是不支持属性注入的,但是可以通过替换容器来实现,也就是今天介绍的:通过 Autofac 来实现属性注入。

autofac简介

Autofac 是一款超赞的.NET IoC 容器 . 它管理类之间的依赖关系, 从而使 应用在规模及复杂性增长的情况下依然可以轻易地修改 . 它的实现方式是将常规的.net类当做 组件 处理.

中文文档:https://autofaccn.readthedocs.io/zh/latest/

为什么要使用属性注入

主要有以下三点:

  1. 减少常用类型的重复注入代码,使构造方法看起来更为简洁,提高阅读性。
  2. 减少或消除因构造方法注入造成子类继承后的 base 调用链。
  3. 并非是满足第一条或第二条就需要使用属性注入来解决,只有当第一、二条发生的情况到达一定的数量。

具体实现

1、引用类库

Autofac
Autofac.Extensions.DependencyInjection

2、在 Program.cs 里替换系统默认容器

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseServiceProviderFactory(new AutofacServiceProviderFactory()) // 使用 autofac 的容器工厂替换系统默认的容器
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});

3、在 Startup.csConfigureServices 里替换控制器的替换规则

public void ConfigureServices(IServiceCollection services)
{
// 替换控制器的替换规则
services.Replace(ServiceDescriptor.Transient<IControllerActivator, ServiceBasedControllerActivator>()); // other configure
services.AddControllers();
}

4、创建 AutowiredAttribute.cs ,用于标识使用属性注入

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

5、创建 AutofacModule.cs ,注册服务

/// <summary>
/// 容器注册类
/// </summary>
public class AutofacModule : Autofac.Module
{
protected override void Load(ContainerBuilder builder)
{
// Register your own things directly with Autofac, like:
builder.RegisterType<HelloService>().As<IHelloService>().InstancePerDependency().AsImplementedInterfaces(); // 获取所有控制器类型并使用属性注入
var controllerBaseType = typeof(ControllerBase);
builder.RegisterAssemblyTypes(typeof(Program).Assembly)
.Where(t => controllerBaseType.IsAssignableFrom(t) && t != controllerBaseType)
.PropertiesAutowired(new AutowiredPropertySelector());
}
} /// <summary>
/// 属性注入选择器
/// </summary>
public class AutowiredPropertySelector : IPropertySelector
{
public bool InjectProperty(PropertyInfo propertyInfo, object instance)
{
// 带有 AutowiredAttribute 特性的属性会进行属性注入
return propertyInfo.CustomAttributes.Any(it => it.AttributeType == typeof(AutowiredAttribute));
}
}

6、在 Startup.cs 的 方法 ConfigureContainer 里注册上一步创建的 Module

// ConfigureContainer is where you can register things directly
// with Autofac. This runs after ConfigureServices so the things
// here will override registrations made in ConfigureServices.
// Don't build the container; that gets done for you. If you
// need a reference to the container, you need to use the
// "Without ConfigureContainer" mechanism shown later.
public void ConfigureContainer(ContainerBuilder builder)
{
builder.RegisterModule(new AutofacModule());
}

示例代码下载:源码

使用效果

[Autowired]
private IHelloService HelloService { get; set; }

在控制器里添加服务属性,然后添加 [Autowired] 特性标识为属性注入即可。

关于属性注入的注意事项

属性注入很好用,但是要慎重使用,因为属性注入会造成类型的依赖关系隐藏,测试不友好等。

建议:在封闭框架时可以使用,但不能大范围使用,只有必须使用属性注入来达到效果的地方才会使用,用来提高使用框架时的编码效率,来达到一些便利,脱离框架层面,编写业务代码时,不得使用。

参考资料

主要参考文章:

使用 autofac 实现 asp .net core 的属性注入

ASP.NETCore 3.0 Autofac替换及控制器属性注入及全局容器使用 - 情·深 - 博客园

autofac 的官方示例:

autofac/Examples: Example projects that consume and demonstrate Autofac IoC functionality and integration

autofac 文档:

Welcome to Autofac’s documentation! — Autofac 5.2.0 documentation

欢迎来到 Autofac 中文文档! — Autofac 4.0 文档

其它:

ASP.NET Core 奇淫技巧之伪属性注入 - 晓晨Master - 博客园

.net core2.0下Ioc容器Autofac使用 - 焰尾迭 - 博客园

基于autofac的属性注入的更多相关文章

  1. Autofac 的属性注入,IOC的坑

    Autofac 是一款优秀的IOC的开源工具,完美的适配.Net特性,但是有时候我们想通过属性注入的方式来获取我们注入的对象,对不起,有时候你还真是获取不到,这因为什么呢? 1.你对Autofac 不 ...

  2. 基于AspectCore打造属性注入

    前言 源自于晓晨在成都.net社区群的一篇文章 <晓晨的ASP.NET Core 奇淫技巧之伪属性注入> 他的思路是 Ioc容器替换 ControllerActivator,因为只能在控制 ...

  3. Autofac 的属性注入方式

    介绍 该篇文章通过一个简单的 ASP.NET MVC 项目进行介绍如何使用 autofac 及 autofac 的 MVC 模块进行依赖注入.注入方式通过构造函数.在编写 aufofac 的依赖注入代 ...

  4. ASP.NET Core中使用Autofac进行属性注入

    一些无关紧要的废话: 作为一名双修程序员(自封的),喜欢那种使用Spring的注解形式进行依赖注入或者Unity的特性形式进行依赖注入,当然,形式大同小异,但结果都是一样的,通过属性进行依赖注入. A ...

  5. WebAPI2使用Autofac实现IOC属性注入完美解决方案

    一.前言 只要你是.NETer你一定IOC,IOC里面你也会一定知道Autofac,上次说了在MVC5实现属性注入,今天实现在WebApi2实现属性注入,顺便说一下autofac的程序集的注入方式,都 ...

  6. .NET领域最为流行的IOC框架之一Autofac WebAPI2使用Autofac实现IOC属性注入完美解决方案 AutoFac容器初步

    .NET领域最为流行的IOC框架之一Autofac   一.前言 Autofac是.NET领域最为流行的IOC框架之一,微软的Orchad开源程序使用的就是Autofac,Nopcommerce开源程 ...

  7. ASP.NETCore 3.0 Autofac替换及控制器属性注入及全局容器使用

    1.Autofac基础使用 参考: https://www.cnblogs.com/li150dan/p/10071079.html 2.ASP.NETCore 3.0 Autofac 容器替换 需要 ...

  8. .net core番外第2篇:Autofac的3种依赖注入方式(构造函数注入、属性注入和方法注入),以及在过滤器里面实现依赖注入

    本篇文章接前一篇,建议可以先看前篇文章,再看本文,会有更好的效果. 前一篇跳转链接:https://www.cnblogs.com/weskynet/p/15046999.html 正文: Autof ...

  9. Java框架spring 学习笔记(六):属性注入

    属性注入:创建对象的时候,向类里面的属性设置值. Java属性注入有三种方法: 使用set方法注入 有参数构造注入 使用接口注入 Spring框架里面的属性注入方式 有参数构造属性注入 set方法属性 ...

随机推荐

  1. Leetcode(106)-从中序与后序遍历序列构造二叉树

    根据一棵树的中序遍历与后序遍历构造二叉树. 注意:你可以假设树中没有重复的元素. 例如,给出 中序遍历 inorder = [9,3,15,20,7] 后序遍历 postorder = [9,15,7 ...

  2. acm 快速傅里叶变换的理解

    A(x)=A4[0](x*x)+x*A4[1](x*x);x=1,w,w*w,w*w*wwi means w^in=4;w=w[4]result shuould bey[0]=A4[0](1*1)+1 ...

  3. IPC$入侵

    一 唠叨一下: 网上关于ipc$入侵的文章可谓多如牛毛,而且也不乏优秀之作,攻击步骤甚至可以说已经成为经典的模式,因此也没人愿意再把这已经成为定式的东西拿出来摆弄. 二 什么是ipc$ IPC$(In ...

  4. Dapr 正式发布1.0

    年前我写了一篇博客<Dapr 已在塔架就位 将发射新一代微服务>, 今天Dapr 正式发布了1.0 : Dapr Runtime v1.0.0 Dapr dotnet SDK v1.0.0 ...

  5. AIoT & IoT

    AIoT & IoT Artificial Intelligence of Things Internet of Things AIoT === AI + IoT 人工智能物联网 === 人工 ...

  6. js & anti craw & crawler spam

    js & anti craw & crawler spam demo & X-Sign , function(t, e, n) { "use strict" ...

  7. Flutter: provider 使用小部件的小部件构建的依赖注入系统

    文档 dependencies: provider: import 'package:dart_printf/dart_printf.dart'; import 'package:flutter/ma ...

  8. PHP反序列化字符串逃逸

    通过CTF比赛了解PHP反序列化,记录自己的学习. 借用哈大佬们的名言 任何具有一定结构的数据,如果经过了某些处理而把结构体本身的结构给打乱了,则有可能会产生漏洞. 0CTF 2016piapiapi ...

  9. springCloud中的注册中心Nacos

    springCloud中的注册中心Nacos 三个模块: 1.注册中心 2.服务提供者(生产者) 提供服务 3.服务消费者(消费者)调用服务 流程:消费者和生产者都要向注册中心注册,注册的是二者中服务 ...

  10. Django Admin 图片路径设置显示为图片(imageField显示方法设置)

    一  使用环境 开发系统: windows IDE: pycharm 数据库: msyql,navicat 编程语言: python3.7  (Windows x86-64 executable in ...