Appearance
自定义注入
AsDI允许自定义自己的注入方式。通过自定义的标注,让容器按定义的方式获取实例。与自定义注册不同的是,它不针对某个类型,只要带自定义的这个标注,都以自定义的方式去获取实例。
下面以自定义一个标注,让容器注入环境变量为例:
- 自定义标注 EnvAttribute
C#
public sealed class EnvAttribute : CustomInjectAttribute
{
private readonly string name;
/// <summary>
/// 获取环境变量
/// </summary>
/// <param name="name">环境变量名称</param>
public EnvAttribute(string name)
{
this.name = name;
}
public override object GetInstance(Type type)
{
if (type != typeof(string)) //不是字符串类型,不能用此标注注入
{
throw new Exception("环境变量只能通过字符串接收");
}
return System.Environment.GetEnvironmentVariable(name);
}
}注意
- 必须要继承 CustomInjectAttribute 并重写 GetInstance 方法
- 要注意被标注的注入对象的类型,如果返回的类型不对应,会导致程序报错
- 使用 EnvAttribute
C#
[Service]
public class UserController
{
private readonly string os, temp;
public UserController([Env("OS")] string os, [Env("TEMP")] string temp)
{
//通过构造函数,注入两个环境变量
this.os = os;
this.temp = temp;
}
public void Print()
{
Console.WriteLine("环境变量 OS = " + os);
Console.WriteLine("环境变量 TEMP = " + temp);
}
}此时,调用UserController的Print方法时,会输出:
sh
> 环境变量 OS = Windows_NT
> 环境变量 TEMP = C:\Users\XXXX\AppData\Local\Temp注意
自定义注入标注可以标注属性、变量、参数,标注在类、方法上无效