我正在学习 Ninject 作为我的第一个 DI 容器,我想所有容器都会有类似的想法,所以这是我的问题。
我有一个类 UserRepository 有一个功能:
//constructor
public UserRepository(Kernel kernel) { _kernel = kernel; }
public UserDataModel CreateNewUser(string title, string firstname,
string lastname, int age ...)
{
//I have the kernel registered everything properly
//Getting a new user object from the kernel
var user = _kernel.Get<UserDataModel>();
user.Title = title;
user.Firstname = firstname;
user.Lastname = lastname;
...
return user;
}
它是使用内核的正确方法吗?我从其他帖子中读到,暴露和传递内核是一个坏主意。如果是这样,正确的方法是什么?
编辑
我的一些代码演示了 tempUser 对象的使用
public int UpdateSaUser(Guid msuserid, UserProfile saprofile,
string accesstoken = "")
{
using (var db = new SaModelContainer())
{
var row1 = MakeNewRow(msuserid, saprofile, accesstoken);
var row2 = db.SaUser.SingleOrDefault(
r => r.MsUserId.Equals(msuserid));
if (row2 == null) { //add new
db.sauth_User.Add(row1);
} else { //modify
var entry = db.Entry(row2);
entry.OriginalValues.SetValues(row2);
entry.CurrentValues.SetValues(row1);
}
return db.SaveChanges();
}
}
private SaUser MakeNewRow(Guid msuserid, UserProfile saprofile,
string accesstoken = "")
{
var row = new SaUser {
MsUserId = msuserid,
Provider = (int)saprofile.Provider,
ProfileId = saprofile.ID,
Email = saprofile.Email,
AccessToken = accesstoken,
FirstName = saprofile.FirstName,
LastName = saprofile.LastName,
FullName = saprofile.FullName,
UserName = saprofile.Username,
DisplayName = saprofile.DisplayName,
Country = saprofile.Country,
DoB = StringParser.ParseDate(saprofile.DateOfBirth),
Gender = (int)saprofile.GenderType,
Language = saprofile.Language,
ProfileURL = saprofile.ProfileURL,
ProfilePictureURL = saprofile.ProfilePictureURL
};
return row;
}