Using AutoFac in WebApi

Using AutoFac in WebApi (I)

The previous article said how to use AutoFac, but there is still a problem: when an interface has multiple implementation classes, how to distinguish the implementation classes?

There are many solutions, such as named < T > and so on, but they all need to register separately. If it is less, it will be a bit troublesome.

Finally, we decided to use generics to solve this problem.

Step 1: add an implementation class: UsersRepository2

    public interface IUsersRepository
    {
        int GetUserIsExists(UsersEntity criteria);

    }

    //Implementation class 1
    public class UsersRepository : IUsersRepository
    {
        Logger log = LogManager.GetLogger("UsersRepository");

        /// <summary>
        /// Get whether the user exists
        /// </summary>
        /// <param name="criteria"></param>
        /// <returns></returns>
        public int GetUserIsExists(UsersEntity criteria)
        {
            string sql = ". . . . ";
. . . . . } }
//Implementation class 2
public class UsersRepository2 : IUsersRepository { Logger log = LogManager.GetLogger("UsersRepository2"); /// <summary> /// Get whether the user exists /// </summary> /// <param name="criteria"></param> /// <returns></returns> public int GetUserIsExists(UsersEntity criteria) { string sql = ". . . . "; . . . . . } }

Step 2: adjust the service interface and implementation class

 1     public enum UsersType
 2     {
 3         /// <summary>
 4         /// Implementation class 1
 5         /// </summary>
 6         [Description("Implementation class 1")]
 7         UsersRepository = 1,
 8         /// <summary>
 9         /// Implementation class 2
10         /// </summary>
11         [Description("Implementation class 2")]
UsersRepository2 = 2,
12 } 13 14 //Adjust service interface 15 public interface IUsersService 16 { 17 int GetUserIsExists<T>(T t, UsersEntity criteria); //Change to generic method here 18 } 19 20 //Adjustment implementation class 21 public class UsersService : IUsersService 22 { 23 //Use here instead IEnumerable<T>type 24 private readonly IEnumerable<IUsersRepository> _usersrepository; 25 public UsersService(IEnumerable<IUsersRepository> usersrepository) 26 { 27 _usersrepository = usersrepository; 28 } 29 30 /// <summary> 31 /// Get whether the user exists 32 /// </summary> 33 /// <param name="criteria"></param> 34 /// <returns></returns> 35 public int GetUserIsExists<T>(T t, UsersEntity criteria) 36 { 37 //According to generics T Get the desired instance object 38 var getinstance = _usersrepository.Where(ob => ob.GetType().Name == t.ToString()).FirstOrDefault(); //Get the specified instance 39 if (getinstance != null) 40 { 41 return getinstance.GetUserIsExists(criteria); 42 } 43 return 0; 44 } 45 }

Step 3: Test

 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         /// Get whether the user exists
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             //Verify that the current user exists
20             var obModel = new UsersEntity()
21             {
22                 Username = username,
23                 Password = Encryption.MD5(password)
24             };
25 
26             //When called here, the enumeration is passed in: UsersType.UsersRepository or UsersType.UsersRepository2
27             var getresult = _usersService.GetUserIsExists(UsersType.UsersRepository, obModel);
28 
29             return Json(new { isexists = getresult > 0 });
30         }
31 
32 
33     }

We set breakpoints on both implementation classes,

When UsersType.UsersRepository is passed, the breakpoint of UsersRepository class comes in,

When passing UsersType.UsersRepository2, the breakpoint of UsersRepository2 class comes in,

Of course, the implementation classes are executed separately. If you want to execute all the implementation classes, just remove the generic filtering in the service class

For example:

 1     public class UsersService : IUsersService
 2     {
 3         //Use here instead IEnumerable<T>type
 4         private readonly IEnumerable<IUsersRepository> _usersrepository;
 5         public UsersService(IEnumerable<IUsersRepository> usersrepository)
 6         {
 7             _usersrepository = usersrepository;
 8         }
 9 
10         /// <summary>
11         /// Get whether the user exists
12         /// </summary>
13         /// <param name="criteria"></param>
14         /// <returns></returns>
15         public int GetUserIsExists<T>(T t, UsersEntity criteria)
16         {
17             //According to generics T Get the desired instance object
18             //var getinstance = _usersrepository.Where(ob => ob.GetType().Name == t.ToString()).FirstOrDefault();  //Get the specified instance
19             //if (getinstance != null)
20             //{
21             //    return getinstance.GetUserIsExists(criteria);
22             //}
23 
24             //Here, adjust the code to execute all the implementation classes
25             var getresult = 0;
26             _usersrepository.ToList().ForEach(item =>
27             {
28                 var gettype = item.GetType().Name;
29                 switch (gettype)
30                 {
31                     case "UsersRepository":
32                         //Other business logic
33                         getresult = item.GetUserIsExists(criteria);
34                         break;
35                     //case 2 .....
36                     //case 3 .....
37                     default:
38                         break;
39                 }
40             });
41             return 0;
42         }
43     }

end.

Tags: ASP.NET SQL less JSON

Posted on Wed, 13 May 2020 10:18:58 -0400 by FrozNic