参考文档
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 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
public interface IUsersRepository { int GetUserIsExists(UsersEntity criteria); } public class UsersRepository : IUsersRepository { Logger log = LogManager.GetLogger("UsersRepository"); /// <summary> /// 获取用户是否存在 /// </summary> /// <param name="criteria"></param> /// <returns></returns> public int GetUserIsExists(UsersEntity criteria) { string sql = "。。。。"; try { //查询sql代码,此处省略。。。。 } catch (Exception ex) { log.Fatal(ex, "获取用户是否存在异常:{0},SQL:{1}", ex.Message, sql); return 0; } } } |
服务类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
//接口 public interface IUsersService { int GetUserIsExists(UsersEntity criteria); } //实现类 public class UsersService : IUsersService { private readonly IUsersRepository _usersrepository; public UsersService(IUsersRepository usersrepository) //通过构造函数注入 { _usersrepository = usersrepository; } /// <summary> /// 获取用户是否存在 /// </summary> /// <param name="criteria"></param> /// <returns></returns> public int GetUserIsExists(UsersEntity criteria) { return _usersrepository.GetUserIsExists(criteria); } } |
在Api接口项目中创建一个AutoFac工具类:AutofacUtil.cs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
public class AutofacUtil { private static IContainer _container; public static void ConfigureContainer() { #region AutoFac IOC容器 var builder = new ContainerBuilder(); try { //builder.RegisterControllers(Assembly.GetCallingAssembly()); //注册mvc控制器 需要引用package Autofac.Mvc //builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired(); //支持Api控制器属性注入 builder.RegisterApiControllers(Assembly.GetCallingAssembly()); //注册所有api控制器 构造函数注入 需要引用package Autofac.WebApi //注册程序集 #region Service var assemblysServices = Assembly.Load("WebApi.Service"); builder.RegisterAssemblyTypes(assemblysServices) .AsImplementedInterfaces() .InstancePerDependency(); #endregion #region Repository var assemblysRepository = Assembly.Load("WebApi.Repository"); builder.RegisterAssemblyTypes(assemblysRepository) .AsImplementedInterfaces() .InstancePerDependency(); #endregion _container = builder.Build(); //创建依赖注入 //设置MVC依赖注入 //DependencyResolver.SetResolver(new AutofacDependencyResolver(_container)); //设置WebApi依赖注入 GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(_container); } catch (Exception ex) { throw new Exception(ex.Message + "\n" + ex.InnerException); } #endregion } /// <summary> /// 从Autofac容器获取对象 /// </summary> /// <typeparam name="T"></typeparam> /// <returns></returns> public static T GetFromFac<T>() { return _container.Resolve<T>(); } } |
在 Global.asax.cs 全局中注册一下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); //AutoFac 注册 AutofacUtil.ConfigureContainer(); } } |
最后在接口中使用:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
public class UsersController : ApiController { private readonly IUsersService _usersService; public UsersController(IUsersService usersService) //使用构造函数注入 { _usersService = usersService; } /// <summary> /// 获取用户是否存在 /// </summary> /// <param name="username"></param> /// <param name="password"></param> /// <returns></returns> [HttpPost] public IHttpActionResult GetUserIsExists(string username, string password) { //验证是否存在当前用户 var obModel = new UsersEntity() { Username = username, Password = Encryption.MD5(password) }; var getresult = _usersService.GetUserIsExists(obModel); return Json(new { isexists = getresult > 0 }); } } |
测试结果:
最后:如果出现 未将对象引用的实例 的错误,检查一下是否引用相应的dll程序集了。
from:https://www.cnblogs.com/peterzhang123/p/12808922.html