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 } } }