Reputation: 1692
Question: Is there a way to use Ninject to inject dependencies into my MVC Models?
First of all, I am new to MVC and DI (and stackoverflow, btw), so I wanted to make sure I'm going down the proper path with this problem. I've been Googling the answer for days, but I can't find a clean explanation... I'm using C#, .NET4, MVC3, Ninject, and VS2010.
Here's the scenario: I have a new user form where a user can set their login, roles, and set other profile data. When this gets submitted, I need to save the login info to the MembershipProvider, the roles to the RoleProvider, etc... Its gets a little hairy because I am using dual providers (Active Directory / local database) as per my project requirements, so there is a bit of logic in determining which provider to save to, if the user already exists, if they are allowed to self-identify any roles, and so on.
I feel like this logic should go in a .Save() method on my model. However, I then need to inject instances of my providers into my model, and Ninject doesn't seem to inject models (at least not using the default setup that the NuGet package comes with). Hence my initial question.
I can think of some alternatives...
So... Is there a way to Ninject the model or do I need to re-factor because I am a newbie at this?
Upvotes: 16
Views: 4928
Reputation: 12567
I would go with option one. It's not overkill - adding a class and an interface is just a few lines of code and it keeps your implementation neat, and maybe later you will want to add more methods... update a user?
Add an interface and class to handle this which your controller uses - ninject will fetch this instance for you. I have written IMembershipAndRoleService as an example.
public interface IMembershipAndRoleService
{
void ProcessNewUser(User newUser);
}
public class YourController : Controller
{
private readonly IMembershipAndRoleService _membershipAndRoleService;
public YourController(IMembershipAndRoleService membershipAndRoleService)
{
_membershipAndRoleService = membershipAndRoleService;
}
[HttpPost]
public ActionResult NewUserFormAction(NewUserForm newUserForm)
{
//process posted form, possibly map / convert it to User then call to save
_membershipAndRoleService.ProcessNewUser(user);
//redirect or return view
}
}
Lastly make the class which implements IMembershipAndRoleService, this class will use your Membership and Role providers OR other interfaces which do, keeping your logic in this class simplified.
Upvotes: 11
Reputation: 9326
If you are using the Ninject.MVC package from NuGet, it will hook into the MVC DependencyResolver, so you can do this to get an instance of a model injected by Ninject.
var model = System.Web.Mvc.DependencyResolver.Current.GetService<MyModel>();
The service architecture is probably a better way to design the app, but for the simple question of "why doesn't my model get injected", it is because you need to create it via the dependency injection container, not via new().
Upvotes: 5