【发布时间】:2011-04-13 22:54:37
【问题描述】:
简而言之:我正在尝试创建一个自定义模型绑定器,它将接受用户类型并获取他们的 id,然后使用服务类来检索强类型对象。
如果有更好的方法,请告诉我。
阐述:
我在我的 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(); - 但它是空的......
注意:我创建模型绑定器的原因 - 所有控制器都需要用户类型,因为我的服务层需要哪种类型的用户正在发出请求,我的服务层中的大多数方法都会有重载ShopUser 或 ClientUser 或系统中的任何其他用户的一件事......
编辑: 我可以很容易地在我的控制器中调用 IAuthenticationService 并获取用户类型并传递到我的域服务层以处理相关任务,但我只想知道如何使用 ModelBindings (以及这样做是否有意义)那样)。
Edit2:是否有使用带有 AOP 的自定义属性和自定义属性调用/绑定/获取 ISomethingService 实例的工作示例?
【问题讨论】:
标签: c# asp.net-mvc-2 .net-3.5 aop ninject