參考文檔 https://www.cnblogs.com/htsboke/p/10956807.html https://www.cnblogs.com/lenmom/p/8510572.html 在WebApi項目中使用AutoFac,結構如下: 首先在Api項目當中引用AutoFac包,如下圖所 ...
參考文檔
https://www.cnblogs.com/htsboke/p/10956807.html
https://www.cnblogs.com/lenmom/p/8510572.html
在WebApi項目中使用AutoFac,結構如下:
首先在Api項目當中引用AutoFac包,如下圖所示:
倉儲類:
1 public interface IUsersRepository 2 { 3 int GetUserIsExists(UsersEntity criteria); 4 5 } 6 7 8 public class UsersRepository : IUsersRepository 9 { 10 Logger log = LogManager.GetLogger("UsersRepository"); 11 12 /// <summary> 13 /// 獲取用戶是否存在 14 /// </summary> 15 /// <param name="criteria"></param> 16 /// <returns></returns> 17 public int GetUserIsExists(UsersEntity criteria) 18 { 19 string sql = "。。。。"; 20 try 21 { 22 //查詢sql代碼,此處省略。。。。
} 28 catch (Exception ex) 29 { 30 log.Fatal(ex, "獲取用戶是否存在異常:{0},SQL:{1}", ex.Message, sql); 31 return 0; 32 } 33 } 34 }
服務類:
1 //介面
public interface IUsersService 4 { 5 int GetUserIsExists(UsersEntity criteria); 6 7 } 8 10 //實現類 11 public class UsersService : IUsersService 12 { 13 private readonly IUsersRepository _usersrepository; 14 public UsersService(IUsersRepository usersrepository) //通過構造函數註入 15 { 16 _usersrepository = usersrepository; 17 } 18 19 /// <summary> 20 /// 獲取用戶是否存在 21 /// </summary> 22 /// <param name="criteria"></param> 23 /// <returns></returns> 24 public int GetUserIsExists(UsersEntity criteria) 25 { 26 return _usersrepository.GetUserIsExists(criteria); 27 } 28 }
在Api介面項目中創建一個AutoFac工具類:AutofacUtil.cs
1 public class AutofacUtil 2 { 3 private static IContainer _container; 4 5 public static void ConfigureContainer() 6 { 7 #region AutoFac IOC容器 8 9 var builder = new ContainerBuilder(); 10 11 try 12 { 13 //builder.RegisterControllers(Assembly.GetCallingAssembly()); //註冊mvc控制器 需要引用package Autofac.Mvc 14 15 //builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired(); //支持Api控制器屬性註入 16 builder.RegisterApiControllers(Assembly.GetCallingAssembly()); //註冊所有api控制器 構造函數註入 需要引用package Autofac.WebApi 17 18 //註冊程式集 19 #region Service 20 var assemblysServices = Assembly.Load("WebApi.Service"); 21 builder.RegisterAssemblyTypes(assemblysServices) 22 .AsImplementedInterfaces() 23 .InstancePerDependency(); 24 #endregion 25 26 #region Repository 27 var assemblysRepository = Assembly.Load("WebApi.Repository"); 28 builder.RegisterAssemblyTypes(assemblysRepository) 29 .AsImplementedInterfaces() 30 .InstancePerDependency(); 31 #endregion 32 33 _container = builder.Build(); //創建依賴註入 34 35 36 //設置MVC依賴註入 37 //DependencyResolver.SetResolver(new AutofacDependencyResolver(_container)); 38 39 //設置WebApi依賴註入 40 GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(_container); 41 } 42 catch (Exception ex) 43 { 44 throw new Exception(ex.Message + "\n" + ex.InnerException); 45 } 46 #endregion 47 } 48 49 /// <summary> 50 /// 從Autofac容器獲取對象 51 /// </summary> 52 /// <typeparam name="T"></typeparam> 53 /// <returns></returns> 54 public static T GetFromFac<T>() 55 { 56 return _container.Resolve<T>(); 57 } 58 59 }
在 Global.asax.cs 全局中註冊一下:
1 public class WebApiApplication : System.Web.HttpApplication 2 { 3 protected void Application_Start() 4 { 5 AreaRegistration.RegisterAllAreas(); 6 GlobalConfiguration.Configure(WebApiConfig.Register); 7 FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 8 RouteConfig.RegisterRoutes(RouteTable.Routes); 9 BundleConfig.RegisterBundles(BundleTable.Bundles); 10 11 //AutoFac 註冊 12 AutofacUtil.ConfigureContainer(); 13 14 } 15 }
最後在介面中使用:
1 public class UsersController : ApiController 2 { 3 private readonly IUsersService _usersService; 4 public UsersController(IUsersService usersService) //使用構造函數註入 5 { 6 _usersService = usersService; 7 } 8 9 10 /// <summary> 11 /// 獲取用戶是否存在 12 /// </summary> 13 /// <param name="username"></param> 14 /// <param name="password"></param> 15 /// <returns></returns> 16 [HttpPost] 17 public IHttpActionResult GetUserIsExists(string username, string password) 18 { 19 //驗證是否存在當前用戶 20 var obModel = new UsersEntity() 21 { 22 Username = username, 23 Password = Encryption.MD5(password) 24 }; 25 var getresult = _usersService.GetUserIsExists(obModel); 26 27 return Json(new { isexists = getresult > 0 }); 28 } 29 30 31 }
測試結果:
最後:如果出現 未將對象引用的實例 的錯誤,檢查一下是否引用相應的dll程式集了。