Skip to content

自动注册

自动注册是AsDI最常用的注册方式。适用于由我们自己建的类型。
带有[Include]的子类标注的的类型会自动被扫描并注册,常用的有[Service]和[Exclude],其中[Service]用于标注服务的实现类型,[Exclude]用于标注不需要容器管理的类型(主要用于排除不需要被容器管理的Interceptor或Proxy)

基本用法

C#
public interface IHelloService
{
    string Hello(string name);
}

[Service]
public class HelloService : IHelloService
{
    public string Hello(string name)
    {
        return "Hello " + name;
    }
}

//或者,只是定义一个类型,不继承接口
[Service]
public class HelloWorld
{
    public string Say()
    {
        return "Hello World !";
    }
}
[Include]
public class Program
{
    /// <summary>
    /// 注入IHelloService
    /// </summary>
    [AutoAssemble]
    public static IHelloService helloService;
    /// <summary>
    /// 注入HelloWorld
    /// </summary>
    [AutoAssemble]
    public static HelloWorld helloWorld;
    static void Main(string[] args)
    {
        AsDIContext.Start();
        Console.WriteLine(helloService.Hello("Jack"));
        Console.WriteLine(helloWorld.Say());
    }
}

输出结果:

sh
> Hello Jack
> Hello World!

注意

  1. [Service] 的标识是必须的
  2. 强烈推荐面向接口编程,如果不继承接口或abstract类型,切面和代理都无法生效

服务的版本

同一个服务接口,可以定义多个实现,多个实现间版本不一致,[service]默认版本是0。注入时,如果没有规定版本,容器会将最高版本的实现注入,如果规定了版本,容器会将相应版本的实现注入

C#
    public interface IHelloService
    {
        string Hello(string name);
    }

    /// <summary>
    /// 版本1:英文输出
    /// </summary>
    [Service(1)]
    public class HelloServiceEn : IHelloService
    {
        public string Hello(string name)
        {
            return "Hello " + name;
        }
    }

    /// <summary>
    /// 版本2:中文输出
    /// </summary>
    [Service(2)]
    public class HelloServiceCN : IHelloService
    {
        public string Hello(string name)
        {
            return "你好 " + name;
        }
    }

    [Include]
    public class Program
    {
        /// <summary>
        /// 默认注入,会注入最高版本
        /// </summary>
        [AutoAssemble]
        public static IHelloService defaultService;

        /// <summary>
        /// 注入版本为1的实现
        /// </summary>
        [AutoAssemble(1)]
        public static IHelloService v1Service;

        static void Main(string[] args)
        {
            AsDIContext.Start();
            Console.WriteLine(defaultService.Hello("Jack"));
            Console.WriteLine(v1Service.Hello("Jack"));
        }
    }

输出结果:

sh
> 你好 Jack
> Hello Jack

沪ICP备2025119739号