• .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相关的代码,上面的代码是最核心的,要使依赖注入生效必须要上面的代码。

     

  • 相关阅读:
    【目标检测】RCNN算法详解
    自己搭建传统ocr识别项目学习
    015. asp.net实现简易聊天室
    014. asp.net实现记住密码的功能
    013. asp.net统计网站访问人数
    012. asp.net生成验证码图片(汉字示例/字母+数字)
    011. asp.net内置对象
    010. 使用.net框架提供的属性
    001. 使用ssh连接不上centos 6.5的解决方法及其解决中文乱码
    009. C#中的WebBrowser控件的属性、方法及操作演示代码(转)
  • 原文地址:https://www.cnblogs.com/Warmsunshine/p/9056770.html
Copyright © 2020-2023  润新知