I am learning Ninject as my first DI container, I guess all containers will have similar idea, so here is my question.
I have a class UserRepository that has a function:
//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;
}
Is it the correct way to use the kernel? I read from other posts that exposing and passing around the kernel is a bad bad idea. If so, what is the correct way to do it?
EDIT
some of my code demostrating the use of a tempUser object
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;
}
You should inject your dependencies also know as dependency Injection. Instead of injecting the kernel.
Example (this is know as constructor injection):
You should probably make an interface of your
UserDataModelso you can mock or stub it in your unit tests. And bind that interface to the correct implementation using ninject see the example. Then there is no need for the attributes.Ninject MVC Documentation
Good mvc example
A list of UserDataModels is not a dependency. I.E. You have some kind of database or other dependecy (WCF Service, Web Service, Entity Framework, nHibernate, …) where the users are coming from that is your dependency.