可以使用扩展方法和泛型类来减少代码重复。
首先,定义一个泛型基类BaseController
,其中T是Controller的类型参数,使得不同控制器可以继承BaseController。然后,在BaseController中定义常见操作的方法,并使用泛型类型参数T进行实现。例如,我们定义了一个名为GetAll
的方法,根据T获取所有的实例。
public abstract class BaseController : Controller where T : class {
protected readonly IDbContext context;
public BaseController(IDbContext context) {
this.context = context;
}
[HttpGet]
public virtual async Task GetAll() {
var entities = await context.Set().ToListAsync();
return Ok(entities);
}
}
然后,扩展Controller
的方法可以被所有控制器使用并且可以通过类型参数T指定操作的实体类型。
public static class ControllerExtensions {
public static async Task GetById(this ControllerBase controller,
int id, IDbContext context) where T : class {
var entity = await context.Set().FindAsync(id);
if (entity == null) {
return NotFound();
}
return Ok(entity);
}
}
最后,我们可以在控制器中继承BaseController
并通过扩展方法调用常见操作方法。例如:
public class ProductController : BaseController {
public ProductController(IDbContext context) : base(context) {}
[HttpGet("{id}")]
public async Task GetById(int id) {
return await this.GetById(id, context);
}
}
这样,我们就可以通过使用泛型类和扩展方法,将常见操作集中到共享的基类中,并让不同控制器可以从中继承和使用它们,从而DRY常见操作。