• .NET 反射和依赖注入


    深度理解依赖注入:http://kb.cnblogs.com/page/45266/

    .NET 反射和依赖注入

    接口反射:

    接口层:接口(interface) 定义为DAL层

    接口(interface)  Idal

    使用反射技术(Reflection) 对Idal 使用工厂模式创建出锁需要的接口实例

    例子:

     string path = "DAL";
        private DAL.Idal createIdal(string str)
        {
            string className = path + ".dal"+str;
            return (DAL.Idal)System.Reflection.Assembly.Load(path).CreateInstance(className);
        }

        public string getstr(string str)
        {
            Idal dal = createIdal(str);
            return dal.getString();
        }

    依赖注入:

    按照依赖注入的需求模式对

     接口:IA

    A:IA

     接口:IB

    B:IB

    在A:IA 里面实现

    IB的实例化(使用反射技术)

    在主程序里就可以实现   IA的实例就可以调用IB的成员函数。

    例子:

    定义类库IDAL

    IA.CS

    using System;

    namespace IDAL
    {
        public interface IA
        {
            string show();
        }
    }
    IB.CS

    using System;

    namespace IDAL
    {
        public interface IB
        {
            string getCode();
        }
    }
    A.CS

    using System;

    namespace IDAL
    {
        public class A : IA
        {
            private IB ib = FACTORY.createIB();

            public string show()
            {
                return ib.getCode();
            }
        }
    }
    B.CS

    using System;

    namespace IDAL
    {
        public class B : IB
        {
            public string getCode()
            {
                return "B";
            }
        }
    }

    FACTORY.cs   //反射时所需的接口工厂

    using System;

    namespace IDAL
    {
        public class  FACTORY
        {
            static string path = "IDAL";
            static string className = "";

            public static IDAL.IA createIA()
            {
                className = path + ".A" ;
                return (IDAL.IA)System.Reflection.Assembly.Load(path).CreateInstance(className);
            }

            public static IDAL.IB createIB()
            {
                className = path + ".B";
                return (IDAL.IB)System.Reflection.Assembly.Load(path).CreateInstance(className);
            }
        }
    }

    调用函数

     IA ia = FACTORY.createIA();
     ia.show();

    转自:http://blog.csdn.net/angelzjk/article/details/5620324

  • 相关阅读:
    Codeforces Round #613 选讲
    Codeforces Round #612 选讲
    Codeforces917E
    一道题20
    LOJ#2244. 「NOI2014」起床困难综合症
    求欧拉回路
    *LOJ#2134. 「NOI2015」小园丁与老司机
    vim操作命令
    常见问题解决
    CentOS7下如何修改mysql的数据目录
  • 原文地址:https://www.cnblogs.com/sheseido/p/2880182.html
Copyright © 2020-2023  润新知