在ASP.NET中使用三層架構(也稱為MVC或MVVM模式)可以有效地降低代碼之間的耦合度,提高系統的可維護性和可擴展性。以下是一些關鍵步驟和最佳實踐:
IBusinessService
和IDataAccessService
。public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddScoped<IBusinessService, BusinessServiceImpl>();
services.AddScoped<IDataAccessService, DataAccessServiceImpl>();
}
public class HomeController : Controller
{
private readonly IBusinessService _businessService;
private readonly IDataAccessService _dataAccessService;
public HomeController(IBusinessService businessService, IDataAccessService dataAccessService)
{
_businessService = businessService;
_dataAccessService = dataAccessService;
}
// Controller actions here
}
public class UserDTO
{
public int Id { get; set; }
public string Name { get; set; }
// Other properties
}
public interface IUserRepository
{
UserDTO GetUserById(int id);
void SaveUser(UserDTO user);
}
public class UserRepository : IUserRepository
{
private readonly ApplicationDbContext _context;
public UserRepository(ApplicationDbContext context)
{
_context = context;
}
public UserDTO GetUserById(int id)
{
// Database query here
}
public void SaveUser(UserDTO user)
{
// Database save operation here
}
}
appsettings.json
)來管理應用程序的配置信息,而不是硬編碼在代碼中。通過以上步驟和最佳實踐,可以有效地降低ASP.NET三層架構中的耦合度,提高系統的可維護性和可擴展性。