2021-03-03

手写IOC

需要了解ioc是什么的可以看看这位大佬的分享

https://www.cnblogs.com/DebugLZQ/archive/2013/06/05/3107957.html

我这里创建的项目是.net web api的项目,因为个人不太擅长前端,所以没创MVC,然后是一个三层架构的,先看一下代码结构吧

一,项目结构

 

 

1.Extension是一个扩展的类库,这里主要是用来存一个读取JSON文件的类

2.Reflex是一个第三方的类库,用来给对象与对象之前做联系的

3.IOC的核心就是低耦合,既然要降低耦合就得依赖抽象,不能依赖细节

所以在DAL里面引用IDAL,BLL里面引用IBLL和IDAL,

Container的话除了Extension和IDAL全部引用

二,代码

首先,在Model中创建一个User类

 public string ID { get; set; } public string Name { get; set; } public string Pwd { get; set; }

 

在IDAL中创建IUserDAL接口

 User GetUser();

 

 

 

 在DAL中创建UserDAL类,实现IUserDAl接口,然后给个简单的模拟数据

return new User(){   ID = "01",   Name = "张思瑞",   Pwd = "0044"}; 

在IBLL中创建IUserBLL接口

User GetUser();

 

 

 在BLL中创建UserBLL类,实现IUserBLL接口,然后注入一个IUserDAL接口

private IUserDAL _userDAL;UserBLL(IUserDAL userDAL){ _userDAL = userDAL;}public User GetUser(){ return _userDAL.GetUser();}

 

 

 到这里基本的框架就已经搭建完了,接下来开始写容器了

在Extension中创建一个GetJson类,用来读取Json文件的数据,需要引用nuget 包 Newtonsoft.Js

 Reflex中创建ObjectFactory类,因为太长了就不截图了

using Extension;using System;using System.Collections.Generic;using System.Reflection;using System.Web;namespace Reflex{ public class ObjectFactory {  private static string PathName = HttpContext.Current.Server.MapPath("~/Assembly.json");  public static T CreateBll<T>(string key)  {   return (T)CreateObject(key);  }  /// <summary>  /// 创建类的实例  /// </summary>  /// <param name="key"></param>  /// <returns>递归</returns>  public static object CreateObject(string key = null)  {   Type type = CreateClass(key);   var ctor = type.GetConstructors();   #region 准备构造函数的参数   List<object> list = new List<object>();   foreach (var item in ctor[0].GetParameters())   {    //Type typedal = item.ParameterType;    //object tapaType = CreateObject(item.ParameterType.Name);    list.Add(CreateObject(item.ParameterType.Name));   }   

No comments:

Post a Comment