在WebApi 中使用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 try21 {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 : IUsersService12 {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 try12 {13 //builder.RegisterControllers(Assembly.GetCallingAssembly()); //注册mvc控制器 需要引用package Autofac.Mvc14 15 //builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired(); //支持Api控制器属性注入16 builder.RegisterApiControllers(Assembly.GetCallingAssembly()); //注册所有api控制器 构造函数注入 需要引用package Autofac.WebApi17 18 //注册程序集19 #region Service20 var assemblysServices = Assembly.Load("WebApi.Service");21 builder.RegisterAssemblyTypes(assemblysServices)22 .AsImplementedInterfaces()23 .InstancePerDependency();24
没有评论:
发表评论