我是使用依赖注入的“新手”,我的问题是:我在哪里可以使用new
Operator?下面我将向您展示一个示例,我想知道我new
是否正确使用了运算符。
该示例适用于带有 的 ASP.NET MVC,CustomControllerFactory
到目前为止一切正常。
首先我有我的实体类Member
:
public partial class Member
{
public Member()
{
this.LoginTries = 0;
}
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public DateTime CreationDate { get; set; }
public int LoginTries { get; set; }
}
然后是一些用户操作的界面:
public interface IDiMembership<TUser>
{
bool Login(string username, string password, bool rememberMe = false);
void Logout();
//This is the Function I am using later and where i am using the new Operator
bool CreateUser(string username, string password, TUser user);
...
}
我的接口实现:
public class DiMembership : IDiMembership<Member>
{
...
public bool CreateUser(string username, string password, Member user)
{
user.PasswordSalt = Crypto.GenerateSalt();
user.Password = Crypto.HashPassword(
string.Format("{0}{1}", password, user.PasswordSalt));
user.Username = username;
user.CreationDate = DateTime.Now;
...
}
我的Controller
电话,这也是我的问题是:CreateUser
使用新的“成员”调用方法或创建新的Member
对象并预填充一些值是否正确?这是 DI 符合还是如何解决问题?
private readonly IDiMembership<Member> _membership;
public AccountController(IDiMembership<Member> membership)
{
_membership = membership;
}
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid &&
_membership.CreateUser(model.Username, model.Password, new Member()))
{
return RedirectToAction("RegisterSuccess");
}
...
}