Injecting into base controller, MVC


I am working on an MVC project, and getting caught up in something that is probably much easier than I'm thinking (but hopefully not, so I feel justified in being an idiot).

I have a lot of views for Create/Edit of objects, just over 300. Instead of having all of these actions inside of my controllers, hey, bright idea, let me create a base controller.

Here is a controller (injection using StructureMap):

public class UserController : Controller { private readonly IUserRepository _repository; public UserController(IUserRepository repository) { _repository = repository; } [HttpGet] [Authorize(Roles = "Administrators, AgencyAdministrators")] public ActionResult Create() { var user = new UserModel { Agency = new AgencyRepository().GetAvailableAgencies(1), Group = new GroupRepository().GetAvailableGroups(1) }; return View(user); } [HttpPost] [Authorize(Roles = "Administrators, AgencyAdministrators")] public ActionResult Create(UserModel model) { // tuple<string, string> (hashed pass, salt) var auth = UserHelper.GenerateSaltedHash(model.PasswordConfirmation); var createResults = _repository.Create(model, auth.Item1, auth.Item2); return RedirectToAction("~/Admin/User/Edit/" + createResults.UserId); } } 

Hopefully you can see what I'm doing (and if it's retarded, please call me a retard and unretard me).

Here is what I am "attempting" to do on my base controller, and I know this is completely wrong, where I want "T" to be my injected repository.

public abstract class BaseCreateEditController<T> : Controller where T : class, new() { private readonly T _repository; public BaseCreateEditController<T>() { _repository = new T(); } [HttpGet] public ActionResult Create() { return View(T); } [HttpPost] public ActionResult Create(T model) { // do stuff or whatever with generic type blah blah } [HttpGet] public ActionResult Edit(int userId) { var item = _repository.Get(userId); return View(item); } } 

So I can remove those actions from my controllers, and have one base controller handling all logic with generics.

Does that make sense? Anyone have an idea to nudge me in the right direction?

by CrappyCoderMVC via /r/csharp

Leave a Reply