.netCore 动态织入

using Microsoft.Extensions.DependencyInjection;
using System;
using System.Reflection;

namespace Aop
{
    public class DI
    {
        public static ServiceProvider services;

    }
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            DI.services = new ServiceCollection().AddTransient(typeof(IPerson), typeof(Student)).BuildServiceProvider();

            var Dec = new Decorator<IPerson>();
            var x = Dec.Instance();

            x.Study();
            x.Eat("apple");
            Console.ReadKey();
        }
    }

    public interface IPerson
    {
        void Study();
        void Eat(string ff);
    }


    public class Student : IPerson
    {
        public void Eat(string ff)
        {
            Console.WriteLine("I am Eating--------...sssssssssss.................");
        }
        public void Study()
        {
            Console.WriteLine("I am studying--------....................");
        }
    }

    public class Decorator<T> : DispatchProxy
    {
        public T Instance()
        {
            var t = typeof(T);
            var s = nameof(DispatchProxy.Create);
            var m = typeof(DispatchProxy).GetMethod(s);

            var obj = m.MakeGenericMethod(t, this.GetType());// 这两个参数,是DispatchProxy.Create的参数,第一个参数要是接口,第二个参数是实现接口的类型。

                                                               // obj.Invoke,返回的是DispatchProxy.Create的执行结果,是继承/实现了两个参数的类型实例。

var dd = obj.Invoke(null, null);//DispatchProxy.Create 这个是静态方法,所以第一个参数为null.这个参数没参数,第二个参数为null
            return (T)dd;
        }

        protected override object Invoke(MethodInfo targetMethod, object[] args)
        {
            Console.WriteLine("执行前");
            targetMethod.Invoke(DI.services.GetService<T>(), args);

            Console.WriteLine("执行后");
            return "asd";
        }
    }
}
核心代码:DispatchProxy.Create

引用在这里

上面的 Instance 也可以写成这样。   只是需要把T 约束为接口

  public T Instance()
        {
            return Create<T, Decorator<T>>();
        }

 mian 函数写成这样也行

      var pp = DispatchProxy.Create<IPerson, Decorator<IPerson>>();
            pp.Study();
            Console.ReadKey();

 

气功波(18037675651)
原文地址:https://www.cnblogs.com/qgbo/p/11881000.html