.Net 6 + WebApi Basics 8 - Generic Repository
2023-01-19 23:27:15  .Net  >> .Net6  >> WebApi

Generic Repository

The Services tier is used to link Repository with UI, but a project may have multiple services while the database properties, like Add or Update functions, are generally the same. Creating a specific Repository class for each service would be more than worth the cost.

Thus, use Generic Repository so that the same Repository code can be used regardless of the type of e different Models.

Implement a Generic Repository

Create a class for generic repository with the following code, based on Sqlsugar, named Repository.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
namespace Repository
{
public class Repository<T> : SimpleClient<T> where T : class, new()
{
public Repository(ISqlSugarClient context = null):base(context)
{
//.NET IOC
base.Context = context;
}
/// <summary>
/// Customized functions
/// </summary>
/// <returns></returns>
public List<T> CommQuery(string json)
{
//base.Context.Queryable<T>().ToList();
return null;
}
}
}

Then, modify Services tier in UserService.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
namespace Services
{
public class UserService
{
//[PREVIOUS] UserRepository
//public UserService(UserRepository userRepository)
//{
// UserRepository = userRepository;
//}
//public UserRepository UserRepository { get; }
//public List<UserClass> GetUsers()
//{
// return UserRepository.GetList();
//}

//[AFTER] Use Generic Repository
public UserService(Repository<UserClass> repository)
{
Repository = repository;
}
public Repository<UserClass> Repository { get; }
public List<UserClass> GetUsers()
{
return Repository.GetList();
}
}
}

As you can see from the above, the generic T calls the UserClass class in Model tier. If you are operating other tables, you only need to modify T in the Service tier.

Finally, inject the generic repository into IOC in Program.cs

1
2
3
4
//builder.Services.AddScoped<UserRepository>();
builder.Services.AddScoped(typeof(Repository<>));
//Service injection keeps same.
builder.Services.AddScoped<UserService>();

Next: .Net 6 + WebApi Basics 9

Last: .Net 6 + WebApi Basics 7


Good Day
😎