我使用asp.net核心。這是使用控制器模型的基本方法。我們什麼時候需要數據類?
public class BookController : Controller
{
private readonly ApplicationDbContext _context { get; set; }
public BookController(ApplicationDbContext context)
{
_context = context;
}
public IActionResult Create(Book model)
{
// adding new model
}
public IActionResult Edit(Book model)
{
// modifying the model
}
public IActionResult Delete(Book model)
{
// removing the model
}
}
我的問題:何時應該/應該在控制器內部實現代碼?我應該/應該在另一個課程中實施它?
事情是這樣的:
public interface IBook
{
int Add(Book book);
int Update(Book book);
int Remove(Book book);
}
public class BookData : IBook
{
private readonly ApplicationDbContext _context { get; set; }
BookData(ApplicationDbContext context)
{
_context = context
}
public int Add(Book model)
{
// ...
return _context.SaveChanges();
}
// other implements...
}
然後,稱這是內部控制:
public IActionResult Create(Book model)
{
var bookData = new BookData(_context);
int result = bookData.Add(model);
// ...
}
對於接口,我覺得可能對情況是有用的:我有一個要求相同的多個控制器行動/方法名稱。
實施例:MessageController
要求3的動作/方法中的至少(Create/Add
,Edit/Update
,Delete/Remove
)。這是相同的,以NotificationController
類,CommentController
類...
因此,該接口可提高到:
public interface IMyService<T> where T : class
{
int Add(T model);
int Update(T model);
int Remove(T model);
}
public class MyService<T> : IMyService<T> where T : class
{
private readonly ApplicationDbContext _context { get; set; }
public MyService(ApplicationDbContext context)
{
_context = context;
}
public int Add(T model)
{
Type type = typeof(model);
if (type == typeof(Book))
{
// adding new book model
}
else if (type == typeof(Comment))
{
// adding new comment model
}
// ...
return -1;
}
// other implements...
}
難道我誤解的東西嗎?