簡而言之:我試圖創建一個自定義模型綁定器,它將採用用戶類型並獲取其ID,然後使用服務類來檢索強類型對象。AOP:自定義模型綁定器屬性使用Ninject
如果有更好的方法來做到這一點,請讓我知道。
Elabaration:
我有我我的DomainService層內的所有綁定ninject設置,3 Web UI中的被掛在域名服務層。每個asp.net mvc應用程序都將綁定加載到內核中。
//我的自定義模型綁定
public class UserModelBinder : IModelBinder
{
private IAuthenticationService auth;
public UserModelBinder(IAuthenticationService _auth, EntityName type,
string loggedonuserid)
{
this.auth = _auth;
CurrentUserType = type;
CurrentUserId = loggedonuserid;
}
public EntityName CurrentUserType { get; private set; }
private string CurrentUserId { get; set; }
public object BindModel(ControllerContext controllerContext,
ModelBindingContext bindingContext)
{
object loggedonuser = null;
if (CurrentUserType == EntityName.Client)
loggedonuser = GetLoggedOnClientUser(CurrentUserId);
else if (CurrentUserType == EntityName.Shop)
loggedonuser = GetLoggedOnShopUser(CurrentUserId);
else
throw new NotImplementedException();
return loggedonuser;
}
public ClientUser GetLoggedOnClientUser(string loggedonuserid)
{
var user = _auth.GetLoggedOnClientUser(loggedonuserid);
if (user == null)
throw new NoAccessException();
return user;
}
public ShopUser GetLoggedOnShopUser(string loggedonuserid)
{
var user = _auth.GetLoggedOnShopUser(loggedonuserid);
if (user == null)
throw new NoAccessException();
return user;
}
}
我Global.aspx.cs
// using NInject to override application started
protected override void OnApplicationStarted()
{
AreaRegistration.RegisterAllAreas();
// hand over control to NInject to register all controllers
RegisterRoutes(RouteTable.Routes);
//how do I instantiate?
ModelBinders.Binders.Add(typeof(object), new
UserModelBinder(null,EntityName.Client, User.Identity.Name));
}
我的問題是IAuthentication是一種服務,它連接到其他的事情,比如倉庫,怎麼辦我真的實例化這適當?我應該創建一個新的NinjectModule嗎?我真的很困惑,所以任何幫助非常感謝。我試圖通過Container.Get(); - 但它是空的...
注意:爲什麼我創建一個modelbinder-所有控制器的原因將需要用戶的類型,因爲我的服務層需要哪種類型的用戶提出請求,我的大多數方法服務層將有重載在那裏將做一件事的ShopUser或ClientUser或系統中的任何其它用戶......
編輯: 我可以於IAuthenticationService我的控制器調用中非常easiy並獲得類型的用戶並傳遞到我的服務層來處理相關的任務,但我只想知道ModelBindings是如何實現的(如果這樣做是有意義的)。
Edit2:是否有一個工作示例使用自定義屬性與AOP與自定義屬性調用/綁定/獲取ISomethingService的實例?
@rmac:服務定位器模式看起來不錯,但AOP方法可能會更好...我改變我的帖子的標題稍微修改,對不起! – Haroon 2011-04-13 10:34:58
您是否也刪除了MVC版本2的約束? MVC 3對注入有更好的支持,我相信有辦法讓它解決每個請求的新模型綁定器實例。這將是最佳解決方案。 – rmac 2011-04-13 12:15:21
我很難想象你想用AOP做什麼。你需要在那裏詳述一下我的想法。 – rmac 2011-04-13 12:17:42