在WebApi 中使用AutoFac
参考文档
https://www.cnblogs.com/htsboke/p/10956807.html
https://www.cnblogs.com/lenmom/p/8510572.html
https://www.cnblogs.com/yaopengfei/p/9479268.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程序集了。
作者:PeterZhang
本文版权归作者和博客园共有,欢迎转载,但必须给出原文链接,并保留此段声明,否则保留追究法律责任的权利。