Skip to content

变量注入

变量注入是指通过当前类型的变量将相应的服务注入。变量注入的前提是当前变量必须被 [AutoAssemble] 标注,容器会自动根据当前变量的类型将相应实例注入。
变量注入的优点是变量使用方便,代码量少,可读性强

提示

  1. 变量的可以是任意访问级别,包括private,但请尽量不要将变量定义成 public
  2. 变量可以是static的变量,但static的变量只会在AsDIContext.Start()时赋值一次

基本用法

C#
[Service]
public class UserController
{
    [AutoAssemble]
    private IUserService Service;

    public void Print()
    {
        Console.WriteLine("Hello " + Service?.GetUserName());
    }
}

public interface IUserService
{
    string GetUserName();
}

[Service]
public class UserService : IUserService
{
    public string GetUserName()
    {
        return "Jack";
    }
}

此时,调用UserController的Print方法时,会输出:

sh
> Hello Jack

注入对应版本

C#
[Service]
public class UserController
{
    [AutoAssemble(1)]
    private IUserService service;

    public void Print()
    {
        Console.WriteLine("Hello " + Service?.GetUserName());
    }
}

public interface IUserService
{
    string GetUserName();
}

[Service(1)]
public class UserService1 : IUserService
{
    public string GetUserName() => "Jack";
}

[Service(2)]
public class UserService2 : IUserService
{
    public string GetUserName() => "Lily";

}

此时,调用UserController的Print方法时,会输出:

sh
> Hello Jack

非必须注入

如果注入时,容器无法实例化相应的类型,在注入时会报错。

C#
[Service]
public class UserController
{
    [AutoAssemble]
    private IUserService service;

    public void Print()
    {
        Console.WriteLine("Hello " + Service?.GetUserName());
    }
}

public interface IUserService
{
    string GetUserName();
}

报错如下:

C#
Unhandled exception. System.Exception: Field [service] cannot be null

如果希望注入时,非必须注入,可以标注[AutoAssemble(false)]

C#
[Service]
public class UserController
{
    [AutoAssemble(false)]
    private IUserService Service;

    public void Print()
    {
        Console.WriteLine("Hello " + Service?.GetUserName());
    }
}

public interface IUserService
{
    string GetUserName();
}

此时,调用UserController的Print方法时,会输出:

sh
> Hello

沪ICP备2025119739号