1.dapper和dapper扩展需要在线安装或者引用DLL即可
使用nuget为项目增加Unity相关的包
2.model类
public class UserInfo { public int Id { get; set; } public string UserName { get; set; } public string Nation { get; set; } public string TrueName { get; set; } public DateTime Birthday { get; set; } public string LocalAddress { get; set; } public int Gender { get; set; } }
3.定义Controller
public class UserController : Controller { // // GET: /User/async static TaskList UserInfolist = new List (); private IUserService service; public UserController(IUserService service) { this.service = service; } public ActionResult Index() { var data = this.service.Get_AllList(); return View(data); } }
4. Index的视图
@model List@{ ViewBag.Title = "index";} index
@if (Model != null && Model.Any()) { foreach (var item in Model) { 用户名 真实姓名 民族 地址 } } @item.UserName @item.TrueName @item.Nation @item.LocalAddress
5.数据访问接口
public interface IUserService
{ /// <summary> /// 查询所有用户 /// </summary> /// <returns></returns> List<UserInfo> GetAllList();/// <summary>
/// 查询所有用户 /// </summary> /// <returns></returns> List<UserInfo> Get_AllList(); }6.定义接口一个实现类SimpleUser
public class SimpleUser:IUserService { public static string constr = ConfigurationManager.ConnectionStrings["SQLConnection"].ConnectionString; IDbConnection conn = new SqlConnection(constr); public ListGetAllList() { var list = new List (); for (int i = 0; i < 10; i++) { list.Add(new UserInfo() { Id = i, UserName = "英文名" + i, Nation = "民族" + i, TrueName = "真实名" + i, LocalAddress = "住址" + i, Gender = i }); } return list; } /// /// 查询所有用户 /// ///public List Get_AllList() { var list = new List (); string sql = @"select top(20) UserName,TrueName,Nation,LocalAddress,Birthday,Gender from UserInfo"; //select Id,UserName,Nation,TrueName,Birthday,LocalAddress,Gender from UserInfo using (SqlConnection conn = new SqlConnection(constr)) { conn.Open(); //dapper标准写法 写原生sql // list = conn.Query (sql,commandType: CommandType.Text).ToList(); //dapper扩展写法 类似EF框架 list = conn.GetList ().ToList(); conn.Close(); } return list; } }
7. 注册依赖使用依赖注入生效
////// 使用nuget为项目增加Unity mvc 5相关的包 /// public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); //注入IOC var container = this.BuildUnityContainer(); DependencyResolver.SetResolver(new UnityDependencyResolver(container)); } IUnityContainer BuildUnityContainer() { var container = new UnityContainer(); container.RegisterType(); return container; } }
8.项目的Global.asax在里面加入上面的注入IoC相关的代码,上面的代码是最核心的,要使依赖注入生效必须要上面的代码。