using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace IBLL { public interface IHelloWord { // 堆代码 duidaima.com string SayHello(string Name); } }(2)BLL层实现接口
using System; using System.Collections.Generic; using System.Linq; using System.Text; using IBLL; namespace BLL { public class HelloWord:IHelloWord { #region IHelloWord 成员 public string SayHello(string Name) { return "Hello_"+Name; } #endregion } }(3)在IOCTest 项目的根目录Web.config下做如下配置(把HelloWord和IHelloWord对应起来):
<appSettings> <add key="IBLL.IHelloWord" value="BLL,BLL.HelloWord"/> </appSettings>说明:key值为接口的全称(命名空间+类名),value值为实现接口的类,两部分组成,逗号前面为生成的dll名称,逗号后面为类名全称(命名空间+类名)。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Collections; using System.Reflection; using System.Configuration; namespace Common { public class IOCReflecter { private static Hashtable s_type=null; static IOCReflecter() { s_type = new Hashtable(); } public static T CreateIntance<T>() { Type t=typeof(T);//key Type type = s_type[t] as Type;//value if (type == null) { string[] AssemblyInfos = ConfigurationManager.AppSettings[t.FullName].Split(','); type = Assembly.Load(AssemblyInfos[0]).GetType(AssemblyInfos[1]); s_type.Add(t, type); } return (T)CreateObject(type) ; } /// <summary> /// 根据typeName获取Type对象 /// </summary> /// <param name="typeName"></param> /// <returns></returns> public static Type GetType(string typeName) { if (string.IsNullOrWhiteSpace(typeName)) { return null; } return Type.GetType(typeName); } /// <summary> /// 获取对象 /// </summary> /// <param name="t"></param> /// <returns></returns> private static object CreateObject(Type t) { if (t == null) { return null; } //查找没有参数的构造函数 //如果需要初始化带参数的构造函数 t.GetConstructors() 获取所有的构造函数 ,it.GetParameters()获取构造函数所有的参数, ConstructorInfo NonParameterConstructors= t.GetConstructors().Where(it=>it.GetParameters().Length==0).FirstOrDefault(); if (NonParameterConstructors == null) { throw new Exception( t.FullName+"必须有一个无参数或默认的构造函数"); } //调用数构造函数创建对象 return t.InvokeMember(null, BindingFlags.CreateInstance, null, null, null); } } }(5)测试
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using IBLL; using Common; namespace IOCTest.Controllers { public class HomeController : Controller { // // GET: /Home/ public ActionResult Index() { //获取实例化对象 IHelloWord hello = IOCReflecter.CreateIntance<IHelloWord>(); ViewBag.Message = hello.SayHello("eric"); return View(); } } } @{ ViewBag.Title = "Index"; } <h2>@ViewBag.Message </h2>
最后上一张截图: