Skip to content

手动注册

所有类型都可以通过手动注册来实现,通常适用于基本类型、delegate、泛型类等。手动注册通过调用ASDIContext.ManualRegister来实现

基本用法

C#
[Include]
public class Program
{
    [AutoAssemble]
    public static string hello;

    [AutoAssemble]
    public static Func<string> sayHello;
    
    static void Main(string[] args)
    {
        AsDIContext.ManualRegister(() => "你好");
        AsDIContext.ManualRegister(Func<string> () =>
        {
            return () => "Hello World";
        });
        AsDIContext.Start();
        Console.WriteLine(hello);
        Console.WriteLine(sayHello());
    }
}

输出结果:

sh
> 你好
> Hello World

注意

在此仅作为示例说明,实际开发中,并不推荐将基本类型注册到容器中使用

服务版本

手动注册,也可以注册不同版本的服务。注入时,如果没有规定版本,容器会将最高版本的实现注入,如果规定了版本,容器会将相应版本的实现注入

C#
    [Include]
    public class Program
    {

        /// <summary>
        /// 默认注入最高版本
        /// </summary>
        [AutoAssemble]
        public static Func<string> sayHello;

        /// <summary>
        /// 指定注入版本
        /// </summary>
        [AutoAssemble(1)]
        public static Func<string> sayHelloEn;

        static void Main(string[] args)
        {
            AsDIContext.ManualRegister(Func<string> () =>
            {
                return () => "Hello World";
            },1); 
            AsDIContext.ManualRegister(Func<string> () =>
            {
                return () => "世界你好";
            },2);
            AsDIContext.Start();
            Console.WriteLine(sayHello());
            Console.WriteLine(sayHelloEn());
        }
    }

输出结果:

sh
> 世界你好
> Hello World

沪ICP备2025119739号