简而言之:我试图创建一个自定义模型绑定器,它将采用用户类型并获取其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