zoukankan      html  css  js  c++  java
  • .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

  • 相关阅读:
    jQuery为啥要提供一个load()方法?
    某大学程序设计竞赛
    【Error】JavaWeb: 严重: Failed to initialize end point associated with ProtocolHandler ["http-bio-8080"]
    form表单和表格
    AJAX入门---DOM操作HTML
    设计模式学习01—单例模式
    Spring MVC 数据验证——validate注解方式
    HOW TO: How to import UUID function into Postgre 9.3
    STM8S 串口应用 UART2 STM8S105
    微信公众平台应用开发框架sophia设计不足(1)
  • 原文地址:https://www.cnblogs.com/sheseido/p/2880182.html
Copyright © 2011-2022 走看看