.NET MVC5+ Dapper+扩展+微软Unity依赖注入实例
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 Task<ArrayList>
        
        List<UserInfo> UserInfolist = new List<UserInfo>();
        
        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<NetIOCUnity.Models.UserInfo>
@{
    ViewBag.Title = "index";
}
<h2>index</h2>
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<div class="well">
    <table class="table">
        <thead>
            <tr>
                <th>用户名</th>
                <th>真实姓名</th>
                <th>民族</th>
                <th>地址</th>
            </tr>
        </thead>
        <tbody>
            @if (Model != null && Model.Any())
            {
                foreach (var item in Model)
                {
                    <tr>
                        <td>@item.UserName </td>
                        <td>@item.TrueName </td>
                        <td>@item.Nation </td>
                        <td>@item.LocalAddress </td>
                    </tr>
                }
            }
        </tbody>
    </table>
</div>
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 List<UserInfo> GetAllList()
        {
            var list = new List<UserInfo>();
            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;
        }
        
        /// <summary>
        /// 查询所有用户
        /// </summary>
        /// <returns></returns>
        public List<UserInfo> Get_AllList()
        {
            var list = new List<UserInfo>();
            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<UserInfo>(sql,commandType: CommandType.Text).ToList();
                //dapper扩展写法 类似EF框架
                  list = conn.GetList<UserInfo>().ToList();
                conn.Close();
            }
            return list;
        }
    }
7. 注册依赖使用依赖注入生效
 /// <summary>
    /// 使用nuget为项目增加Unity mvc 5相关的包
    /// </summary>
    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<IUserService, SimpleUser>();
            return container;
        }  
    }
8.项目的Global.asax在里面加入上面的注入IoC相关的代码,上面的代码是最核心的,要使依赖注入生效必须要上面的代码。
 
                    
                     
                    
                 
                    
                
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号