欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

在WebApi 中使用AutoFac

程序员文章站 2023-03-26 15:30:45
参考文档 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,结构如下:

在WebApi 中使用AutoFac

首先在api项目当中引用autofac包,如下图所示:

在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     }

测试结果:

在WebApi 中使用AutoFac

 

最后:如果出现 未将对象引用的实例 的错误,检查一下是否引用相应的dll程序集了。