參考文檔
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,結構如下:

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
出處:https://www.cnblogs.com/peterzhang123
本文版權歸作者和部落格園共有,歡迎轉載,但必須給出原文連結,并保留此段聲明,否則保留追究法律責任的權利。