在需要时正确创建对象的方法

时间:2012-07-10 12:37:34

标签: asp.net-mvc dependency-injection ninject

我正在学习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;
}

1 个答案:

答案 0 :(得分:2)

您应该注入您的依赖项,也称为依赖注入。而不是注入内核。

示例(这称为构造函数注入):



private UserDataModel _userDataModel;

[Inject]
public UserRepository(UserDataModel userDataModel)
{
    _userDataModel = userDataModel;
}

//Any other method can now use _userDataModel

您应该创建UserDataModel的界面,以便在单元测试中模拟或存根。并使用ninject将该接口绑定到正确的实现,请参阅示例。然后就不需要属性了。

Ninject MVC Documentation

Good mvc example

UserDataModel列表不是依赖项。 I.E.您有某种数据库或其他依赖(WCF服务,Web服务,实体框架,nHibernate,...),用户来自这是您的依赖。



public UserRepository(EntityFrameworkContext context)
{
    //The entity framework context is the dependency that you don't want to test.
    _context = context;
}

public List GetAllUsers()
{
   return _context.Users.ToList();
}