3-使用業務層表示層(MVC)
在此示例中,我們將使用 Presentation 層中的 Business 層。我們將使用 MVC 作為表示層的示例(但你可以使用任何其他表示層)。
我們首先需要註冊 IoC(我們將使用 Unity,但你可以使用任何 IoC),然後編寫我們的表示層
3-1 在 MVC 中註冊 Unity 型別
3-1-1 新增“ASP.NET MVC 的 Unity bootstrapper”NuGet 支援
3-1-2 新增 UnityWebActivator.Start(); 在 Global.asax.cs 檔案中(Application_Start()
函式)
3-1-3 修改 UnityConfig.RegisterTypes 函式如下
public static void RegisterTypes(IUnityContainer container)
{
// Data Access Layer
container.RegisterType<DbContext, CompanyContext>(new PerThreadLifetimeManager());
container.RegisterType(typeof(IDbRepository), typeof(DbRepository), new PerThreadLifetimeManager());
// Business Layer
container.RegisterType<IProductBusiness, ProductBusiness>(new PerThreadLifetimeManager());
}
3-2 使用業務層 @表示層(MVC)
public class ProductController : Controller
{
#region Private Members
IProductBusiness _productBusiness;
#endregion Private Members
#region Constractors
public ProductController(IProductBusiness productBusiness)
{
_productBusiness = productBusiness;
}
#endregion Constractors
#region Action Functions
[HttpPost]
public ActionResult InsertForNewCategory(string productName, string categoryName)
{
try
{
// you can use any of IProductBusiness functions
var newProduct = _productBusiness.InsertForNewCategory(productName, categoryName);
return Json(new { success = true, data = newProduct });
}
catch (Exception ex)
{ /* log ex*/
return Json(new { success = false, errorMessage = ex.Message});
}
}
[HttpDelete]
public ActionResult SmartDeleteWithoutLoad(int productId)
{
try
{
// deletes product without load
var deletedProduct = _productBusiness.DeleteWithoutLoad(productId);
return Json(new { success = true, data = deletedProduct });
}
catch (Exception ex)
{ /* log ex*/
return Json(new { success = false, errorMessage = ex.Message });
}
}
public async Task<ActionResult> SelectByCategoryAsync(int CategoryId)
{
try
{
var results = await _productBusiness.SelectByCategoryAsync(CategoryId);
return Json(new { success = true, data = results },JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{ /* log ex*/
return Json(new { success = false, errorMessage = ex.Message },JsonRequestBehavior.AllowGet);
}
}
#endregion Action Functions
}