.NET MVC5+ Dapper+扩展+AutoFac自动注入实现


1、首先创建一个MVC项目 定义Model 层  view 层 index.cshtml  控制器层Controllers等文件

2、在线安装或者引用dapper 以及扩展相关包 同时Autofac 的相关包以及 Autofac.Asp.Net.Mvc5 包之类

3、定义Model  

using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace AutofacMVC.Models { /// <summary>
    /// 定义Model  /// </summary>
    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; } } }

4、 创建文件夹Repository   定义UserInfoRepository 实现IUserInfoRepository仓储接口

using AutofacMVC.IRepository; using AutofacMVC.Models; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Data.SqlClient; using System.Linq; using System.Web; using Dapper; using DapperExtensions; namespace AutofacMVC.Repository { /// <summary>
    /// 
    /// 创建文件夹Repository 定义UserInfoRepository 实现IUserInfoRepository仓储接口 /// 
    /// </summary>
    public class UserInfoRepository : IUserInfoRepository { public static string constr = ConfigurationManager.ConnectionStrings["SQLConnection"].ConnectionString; IDbConnection conn = new SqlConnection(constr); private List<UserInfo> UserInfos = new List<UserInfo>(); 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; } public IEnumerable<UserInfo> GetAll() { return UserInfos; } } }

 5、创建文件夹IRepository 用于存放仓储接口IUserInfoRepository

using AutofacMVC.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AutofacMVC.IRepository { /// <summary>
    /// 创建文件夹IRepository 用于存放仓储接口IUserInfoRepository /// 添加IUserInfoRepository.cs 继承IDependency /// 我们可以定义IDependency接口的类型,其他任何的接口都需要继承这个接口。 /// </summary>
    public interface IUserInfoRepository : IDependency { /// <summary>
        /// 查询所有用户 /// </summary>
        /// <returns></returns>
        List<UserInfo> GetAllList(); /// <summary>
        /// 查询所有用户 /// </summary>
        /// <returns></returns>
        List<UserInfo> Get_AllList(); IEnumerable<UserInfo> GetAll(); } }

 6、Controller 这里用构造器注入

using AutofacMVC.IRepository; using AutofacMVC.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace AutofacMVC.Controllers { public class UserController : Controller { List<UserInfo> UserInfolist = new List<UserInfo>(); private IUserInfoRepository _service; //构造器注入
        public UserController(IUserInfoRepository service) { this._service = service; } //属性注入 // public IUserInfoRepository repository { get; set; }

        public ActionResult Index() { var data = this._service.Get_AllList(); return View(data); }   } }

7、index

@model List<AutofacMVC.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>

8、

自动注入

    Autofac提供一个RegisterAssemblyTypes方法。它会去扫描所有的dll并把每个类注册为它所实现的接口。既然能够自动注入,那么接口和类的定义一定要有一定的规律。可以定义IDependency接口的类型,其他任何的接口都需要继承这个接口。

 

IRepository在该文件夹增加一个接口类

using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AutofacMVC.IRepository { /// <summary>
    /// Autofac提供一个RegisterAssemblyTypes方法。它会去扫描所有的dll并把每个类注册为它所实现的接口。既然能够自动注入,那么接口和类的定义一定要有一定的规律。我们可以定义IDependency接口的类型,其他任何的接口都需要继承这个接口。 /// </summary>
    public interface IDependency { } }

9、更改IUserInfoRepository.cs 继承IDependency即可   代码已在上面改写

IUserInfoRepository 一一注入的话 该接口文件代码是

using AutofacMVC.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace AutofacMVC.IRepository { /// <summary>
    /// 创建文件夹IRepository 用于存放仓储接口IUserInfoRepository/// </summary>
    public interface IUserInfoRepository { /// <summary>
        /// 查询所有用户 /// </summary>
        /// <returns></returns>
        List<UserInfo> GetAllList(); /// <summary>
        /// 查询所有用户 /// </summary>
        /// <returns></returns>
        List<UserInfo> Get_AllList(); IEnumerable<UserInfo> GetAll(); } }

 

10、注入工作在Global.asax 文件中进行

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Optimization; using System.Web.Routing; using Autofac; using Autofac.Builder; using Autofac.Integration.Mvc; using System.IO; using AutofacMVC.IRepository; using System.Reflection; namespace AutofacMVC1 { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); #region 自动注入
            //创建autofac管理注册类的容器实例
            var builder = new ContainerBuilder(); Assembly[] assemblies = Directory.GetFiles(AppDomain.CurrentDomain.RelativeSearchPath, "*.dll").Select(Assembly.LoadFrom).ToArray(); //注册所有实现了 IDependency 接口的类型
            Type baseType = typeof(IDependency); builder.RegisterAssemblyTypes(assemblies) .Where(type => baseType.IsAssignableFrom(type) && !type.IsAbstract) .AsSelf().AsImplementedInterfaces() .PropertiesAutowired().InstancePerLifetimeScope(); //注册MVC类型
 builder.RegisterControllers(assemblies).PropertiesAutowired(); builder.RegisterFilterProvider(); var container = builder.Build(); DependencyResolver.SetResolver(new AutofacDependencyResolver(container)); #endregion


            #region 手动一个一个的进行注入

            // //创建autofac管理注册类的容器实例 // var builder = new ContainerBuilder(); // //为这个容器注册它可以管理的类型 // //builder的Register方法可以通过多种方式注册类型。 // builder.RegisterType<UserInfoRepository>().As<IUserInfoRepository>(); // //使用Autofac提供的RegisterControllers扩展方法来对程序集中所有的Controller一次性的完成注册 // builder.RegisterControllers(Assembly.GetExecutingAssembly());//生成具体的实例 // //如果使用属性注入 就把上面这句改为
            ////builder.RegisterControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired(); // 这样支持属性注入
            // var container = builder.Build(); // //下面就是使用MVC的扩展 更改了MVC中的注入方式. // DependencyResolver.SetResolver(new AutofacDependencyResolver(container));


            #endregion } } }

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM