【发布时间】:2011-01-04 10:39:09
【问题描述】:
我正在构建一个 ASP.NET MVC 应用程序,该应用程序使用 DDD(域驱动设计)方法和由 NHibernate 处理的数据库访问。我有域模型类(管理员),我想通过 IOC 容器(例如 Castle Windsor)将依赖项注入其中,如下所示:
public class Administrator
{
public virtual int Id { get; set; }
//.. snip ..//
public virtual string HashedPassword { get; protected set; }
public void SetPassword(string plainTextPassword)
{
IHashingService hasher = IocContainer.Resolve<IHashingService>();
this.HashedPassword = hasher.Hash(plainTextPassword);
}
}
我基本上想为 SetPassword 方法注入 IHashingService 而不直接调用 IOC 容器(因为这被认为是 IOC 反模式)。但我不知道该怎么做。我的 Administrator 对象要么通过 new Administrator(); 实例化,要么通过 NHibernate 加载,那么如何将 IHashingService 注入 Administrator 类?
再想一想,我这样做的方式是否正确?我希望避免让我的代码库乱七八糟......
currentAdmin.Password = HashUtils.Hash(password, Algorithm.Sha512);
...而是让域模型本身来处理散列并将其巧妙地封装起来。我可以设想另一个开发人员不小心选择了错误的算法,并有一些密码为 Sha512,一些密码为 MD5,一些使用一种盐,一些使用不同的盐等等。相反,如果开发人员正在编写......
currentAdmin.SetPassword(password);
...那将隐藏这些细节并解决上面列出的问题,不是吗?
【问题讨论】:
标签: asp.net-mvc nhibernate inversion-of-control castle-windsor ioc-container