反射获取对象

本文介绍了如何利用C#的反射能力从metadata中获取对象,通过创建解决方案、项目引用以及修改appsettings.json配置文件来降低程序间的耦合度。通过静态类SimpleFactory在Main方法中的调用来演示这一过程,强调了这种做法在支持扩展如Oracle数据库时的优势。
摘要由CSDN通过智能技术生成

反射:程序员的快乐!
反射是System.Reflection命名空间,可以读取metadata,并使用metadata;是微软提供的一个帮助类库;metadata:是一个清单数据,只是记录有什么,而不是展示所有的实现;明细账本。

1. 创建一个NetCore 解决方案(Solution),新建一个project,命名为Test.AspNetCore.DB.Interface

namespace Test.AspNetCore.DB.Interface
{
    /// <summary>
    /// 数据访问类抽象
    /// </summary>
    public interface IDBHelper
    {
        void Query();
    }
}

2. 创建另外一个project引用这个接口(需要引用上面的project)

namespace Test.AspNetCore.DB.MySql
{
    public class MySqlHelper : IDBHelper
    {
        public MySqlHelper()
        {
            Console.WriteLine($"{this.GetType().Name}被构造");
        }

        public void Query()
        {
            Console.WriteLine("{0}.Query", this.GetType().Name);
        }
    }
}

3. 在主程序这边,修改配置文件appsettings.json

{  
  "MySqlConfig": "Test.AspNetCore.DB.MySql.MySqlHelper,Test.AspNetCore.DB.MySql.dll"
}

还有一点,appsettings.json属性记得设置:始终复制

添加一个静态类SimpleFactory

namespace Test.AspNetCore.Reflecttion
{
    public class SimpleFactory
    {
        public static IDBHelper CreateMySqlInstance()
        {
            string ReflictionConfig = CustomConfigManager.GetConfig("MySqlConfig");
            string tyepName= ReflictionConfig.Split(",")[0];
            string dllName = ReflictionConfig.Split(",")[1];

            //Assembly assembly = Assembly.Load(dllName); //Dll名称,不需要后缀 
            Assembly assembly = Assembly.LoadFrom(dllName); //dll名称(需要后缀) 
            //获取类型
            Type type = assembly.GetType(tyepName); 
            //创建对象
            object obj = Activator.CreateInstance(type);  
            return obj as IDBHelper;
        } 
    }

    public static class CustomConfigManager
    {
        //Core 读取配置文件:appsettings 需要引用下面两个包
        //1.Microsoft.Extensions.Configuration;
        //2.Microsoft.Extensions.Configuration.Json 
        public static string GetConfig(string key)
        {
            var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");  //默认读取  当前运行目录
            IConfigurationRoot configuration = builder.Build();
            string configValue = configuration.GetSection(key).Value;
            return configValue;
        }
    }
}

在Main方法里调用(需要添加引用Test.AspNetCore.DB.Interface 和 Test.AspNetCore.DB.MySql)

namespace Test.AspNetCore.Reflecttion
{
    class Program
    {        
        static void Main(string[] args)
        {
            //通过读取配置文件,利用反射获取MySqlHelper对象,赋值给接口dBHelper
            IDBHelper dBHelper=  SimpleFactory.CreateMySqlInstance();
            dBHelper.Query();
        }
    }
}

输出:

Solution结构:

这样的话,减少程序之间的耦合,“高内聚,低耦合”。如果需要扩展程序,比如对Orcale的支持,仅仅需要添加一个project,然后修改配置文件即可。

namespace Test.AspNetCore.DB.Orcale
{
    public class OrcaleHelper : IDBHelper  //不要忘了继承IDBHelper
    {
        public void Query()
        {
            Console.WriteLine("oracle");
        }
    }
}
namespace Test.AspNetCore.Reflecttion
{
    public class SimpleFactory
    {
        public static IDBHelper CreateMySqlInstance()
        {
            string ReflictionConfig = CustomConfigManager.GetConfig("MySqlConfig");
            string tyepName= ReflictionConfig.Split(",")[0];
            string dllName = ReflictionConfig.Split(",")[1];

            //Assembly assembly = Assembly.Load(dllName); //Dll名称,不需要后缀 
            Assembly assembly = Assembly.LoadFrom(dllName); //dll名称(需要后缀)             
            Type type = assembly.GetType(tyepName); 
            object obj = Activator.CreateInstance(type);  
            return obj as IDBHelper;
        } 

        //添加对Orcale的支持
        public static IDBHelper CreateOrcaleInstance()
        {
            string ReflictionConfig = CustomConfigManager.GetConfig("OrcaleConfig");
            string tyepName= ReflictionConfig.Split(",")[0];
            string dllName = ReflictionConfig.Split(",")[1];

            Assembly assembly = Assembly.LoadFrom(dllName); //dll名称(需要后缀)            
            Type type = assembly.GetType(tyepName); 
            object obj = Activator.CreateInstance(type);  
            return obj as IDBHelper;
        } 
    }

    public static class CustomConfigManager
    {
        //Core 读取配置文件:appsettings 需要引用下面两个包
        //1.Microsoft.Extensions.Configuration;
        //2.Microsoft.Extensions.Configuration.Json 
        public static string GetConfig(string key)
        {
            var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");  //默认读取  当前运行目录
            IConfigurationRoot configuration = builder.Build();
            string configValue = configuration.GetSection(key).Value;
            return configValue;
        }
    }
}
​
{
  "MySqlConfig": "Test.AspNetCore.DB.MySql.MySqlHelper,Test.AspNetCore.DB.MySql.dll",
  "OrcaleConfig": "Test.AspNetCore.DB.Orcale.OrcaleHelper,Test.AspNetCore.DB.Orcale.dll"
}

​

 不要忘记添加引用:Test.AspNetCore.DB.Orcale

namespace Test.AspNetCore.Reflecttion
{
    class Program
    {        
        static void Main(string[] args)
        {
            //通过读取配置文件,利用反射获取MySqlHelper对象,赋值给接口dBHelper
            IDBHelper dBHelper=  SimpleFactory.CreateOrcaleInstance();
            dBHelper.Query();
        }
    }
}

以上,仅为个人练习笔记,如有错误,敬请谅解!

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值