autofac 泛型注入 简单试验

1.概要

泛型注入

2.代码

using Autofac;
using System;

namespace AutoFac泛型
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("AutoFac泛型");
            Program p = new Program();
            p.main();
            Console.ReadKey();
        }
        private void main()
        {
            test1();
            test2();
        }
        /// 
        /// 普通反射注册
        /// 
        private void test1()
        {
            var builder = new ContainerBuilder();
            builder.RegisterType>();
            IContainer container = builder.Build();
            B a = container.Resolve>();
            int b = a.fun(1, 2);
            Console.WriteLine(b);
        }
        /// 
        /// 以泛型的方式注册
        /// 
        private void test2()
        {
            var builder = new ContainerBuilder();
            builder.RegisterGeneric(typeof(B<>));
            IContainer container = builder.Build();
            B a = container.Resolve>();
            int b = a.fun(1, 2);
            Console.WriteLine(b);
        }
        interface IA
        {
            int add(int a, int b);
        }
        class A1 : IA
        {
            public int add(int a, int b)
            {
                return a + b;
            }
        }
        class A2 : IA
        {
            public int add(int a, int b)
            {
                return a + b;
            }
        }
        class B where T : IA, new()
        {
            T t = new T();
            public int fun(int a, int b)
            {
                return t.add(a, b);
            }
        }
    }
}

3.运行结果

AutoFac泛型
3
3

你可能感兴趣的:(c#,开发语言,autofac,泛型)