Autofac Lambda表达式组件注册与服务解析

1 编写组件

    /// <summary>
    /// Lambda表达式组件
    /// </summary>
    public class LambdaComponentDemo
    {
        public void Run()
        {
            Console.WriteLine("LambdaComponentDemo.Run");
        }
    }

    public class LambdaComponentDemo_1 : LambdaComponentDemo
    {
        public new void Run()
        {
            Console.WriteLine("LambdaComponentDemo_1.Run");
        }
    }

    public class LambdaComponentDemo_2 : LambdaComponentDemo
    {
        public new void Run()
        {
            Console.WriteLine("LambdaComponentDemo_2.Run");
        }
    }

2 注册组件

            // 注册Lambda表达式组件
            builder.Register<LambdaComponentDemo>((c, p) => {
                int typeId = p.Named<int>("typeId");
                if(typeId == 1)
                {
                    return new LambdaComponentDemo_1();
                }
                else if(typeId == 2)
                {
                    return new LambdaComponentDemo_2();
                }
                else
                {
                    return new LambdaComponentDemo();
                }
            });

3 解析服务

var service_lambda = scope.Resolve<LambdaComponentDemo>(new NamedParameter("typeId", 1));

4 完整测试代码

    class Program
    {
        private static IContainer container;

        static void Main(string[] args)
        {
            var builder = new ContainerBuilder();
            
            // 注册Lambda表达式组件
            builder.Register<LambdaComponentDemo>((c, p) => {
                int typeId = p.Named<int>("typeId");
                if(typeId == 1)
                {
                    return new LambdaComponentDemo_1();
                }
                else if(typeId == 2)
                {
                    return new LambdaComponentDemo_2();
                }
                else
                {
                    return new LambdaComponentDemo();
                }
            });

            container = builder.Build();

            using(var scope= container.BeginLifetimeScope())
            {
                var service_lambda = scope.Resolve<LambdaComponentDemo>(new NamedParameter("typeId", 1));
                service_lambda.Run(); // LambdaComponentDemo.Run
                ((LambdaComponentDemo_1)service_lambda).Run(); // LambdaComponentDemo_1.Run
            }

            Console.Read();
        }
    }

5 测试结果

 

posted @ 2021-02-25 19:39  温故纳新  阅读(138)  评论(0编辑  收藏  举报