需要了解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));
}
#endregion
return Activator.CreateInstance(type, list.ToArray());
}
/// <summary>
/// 獲取Type
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
private static Type CreateClass(string key)
{
string AssemblyData = https://www.cnblogs.com/issirui/p/GetJson.Readjson(key, PathName);
Assembly assembly = Assembly.Load(AssemblyData.Split(',')[0]);
Type type = assembly.GetType(AssemblyData.Split(',')[1]);
return type;
}
}
}
接下來就是使用IOC容器了
在Container中添加一個叫Assembly的json檔案
//注冊類 //“DAL”是程式集的名稱 “DAL.UserDAL”是程式集的名稱加上類名 //中間用逗號隔開 "IUserDAL": "DAL,DAL.UserDAL", "IUserBLL": "BLL,BLL.UserBLL"

創建一個web api控制器
IUserBLL _userBLL;
UserController()
{
_userBLL = ObjectFactory.CreateBll<IUserBLL>("IUserBLL");
}
public string GetUser()
{
return _userBLL.GetUser().Name;
}

接下來應該可以除錯了,讓我們運行起來看一下
好了,報錯了,索引超出界限,讓我看看是什么原因,我要下班了,明天再來更新
好了,改完了,因為我們那個UserBLL里面的建構式我們沒有設定成公共的,所以我們第三方檢測不到,加上public就行了

語言及其匱乏,沒有過多的解釋啊,我真的下班了
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/265523.html
標籤:C#
下一篇:Redis五種資料結構
