Inject object to the constructor of controller using unity container - c#

I couldn’t find any similar issue so I’m writing this post. There is sample controller with private field IBaseClass. Sample code looks like follows:
public class TmpController : Controller
{
private IBaseClass _baseClass;
public TmpController()
{
_baseClass = new BaseClass(this);
}
}
public interface IBaseClass
{
//...
}
public class BaseClass : IBaseClass
{
protected TmpController TmpController;
public BaseClass(TmpController tmpController)
{
TmpController = tmpController;
}
//IBaseClass implementation
}
My question is; how to inject BaseClass object to the constructor of TmpController using Unity framework?
I want to make my controller "slimmer". I want to put the logic about validation and preparing dataSource of my controls like comboBox etc. to different class. I try to make some kind of SOC in my .Web project in that very specific case, which will make my controller easier to read and maintain. I'm using approach one controller per one view but I met the case with very complex form. Currently I have controller with more than 3000 lines of code and it's hard to maintain so I want to do something with it.
And yes I'm using Services and Repositories but the problem is about validation of ViewModels, mapping ViewModel objects into DTOs and backwards, preparing data source of given components etc.

#Razem, what you guess from my comment is correct. And the minus point you described is also valid.
What you are asking "Service depending on the controller" can surely be achieved but that would be a bad design.
Currently BaseClass is only dependent on TempController. How would you handle the scenario when you need the BaseClass in some other controller also? The code will start breaking and you will end up adding new dependency to BaseClass.
Also as per the design recommendations Top Layers should be dependent on the Bottom Layers not the vice versa.
Being said that, you can still achieve the feature you are looking for that too by making controller dependent on the IBaseClass.
I am not sure the specific reasons you need to access controller inside BaseClass. I have made certain assumptions while creating following suggestions. One of such assumption is BaseClass, IBaseClass and Controller classes are part of the same assembly.
//Have a BaseController Class with the properties and/or method which you will be using in the `BaseClass` class and make them virtual so that derived controller classes can override them to have specific implementation.
public class BaseController : Controller
{
public virtual string ControllerMethod()
{
return "Controller Method from Base Controller";
}
public virtual string RandomValue
{
get
{
return "Random value from Base Controller";
}
}
}
Create a method in IBaseClass which will Set the Controller for it.
public interface IBaseClass
{
void SetController(BaseController controller);
void Method1();
}
public class BaseClass : IBaseClass
{
private BaseController controller;
public void SetController(BaseController controller)
{
this.controller = controller;
}
public void Method1()
{
var str = this.controller.RandomValue;
}
}
And derive the TempController from the BaseController and make it dependent on IBaseClass. And in the constructor of TempController call SetController method of IBaseClass by passing this argument to it. You also can override method/properties of BaseController here.
After this you can call any method of IBaseClass without passing controller instance to it.
public class TempController : BaseController
{
private IBaseClass baseClass;
public HomeController(IBaseClass productService)
{
this.baseClass = productService;
this.baseClass.SetController(this);
}
public override string RandomValue
{
get
{
return "Random value from Derived Class.";
}
}
public ActionResult Index()
{
this.baseClass.Method1();
ViewBag.Title = "Home Page";
return View();
}
}
Install nuget package Unit.Mvc in your web project. Open file Unity.Config located under App_Start folder and change method RegisterTypes as following.
public static void RegisterTypes(IUnityContainer container)
{
container.RegisterType<IBaseClass, BaseClass>(new PerRequestLifetimeManager());
}
I am sure I don't need to explain how this is going to work.
P.S. : You need to make sure that you calls IBaseClass.SetController method in controller constructor to avoid NullReferenceException when you use controller in BaseClass. This is small overhead you need to take to achieve good and maintainable design.

Related

Get base class Member of controller in OnEntry in OnMethodBoundaryAspect in PostSharp

I want access base class member in our Log Aspect Class. I have one base controller & that controller inherit by Test controller & in Test Controller i implemented AOP Aspect.
In BaseContoller i have a member _userSession. I initializing _userSession when BaseContoller's Constructor is call. And after call TestController first AOP Aspect is called. I want Access _userSession on OnEntry method of AOP.
LogAspect Class
[Serializable]
[MulticastAttributeUsage(MulticastTargets.Method)]
public class LogAspect:PostSharp.Aspects.OnMethodBoundaryAspect
{
public object UserData;
public override void OnEntry(PostSharp.Aspects.MethodExecutionArgs args)
{
LogManager.Info(string.Format("Starting - {0}-{0}",args.Instance, new StackTrace().GetFrame(1).GetMethod().Name));
// want access PCX.Portal.Controllers.BaseController._userSession member here its showing in quick watch like this
//((PCX.Portal.Controllers.BaseController)(args.Instance))._userSession
LogManager.Info(string.Format("User data - {0}", FrameworkHelper.Helper.JSONHelper.GetJSON(UserData)));
if(args.Arguments.Count>0)
{
foreach (var item in args.Arguments)
{
LogManager.Info(string.Format("arguments - {0}", FrameworkHelper.Helper.JSONHelper.GetJSON(item)));
}
}
base.OnEntry(args);
}
Base controller
public class BaseController : Controller
{
public UserSession _userSession { set; get; }
AuthenticationManager _authenticationManager = new AuthenticationManager();
public BaseController()
{
//initializing _userSession here
_userSession.userid=4 ;
_userSession.customerId=5 ;
}
}
Test Controller
[LogAspect]
public class TestController : BaseController
{
public ActionResult Index()
{
return View();
}
}
As documentation states:
MethodExecutionArgs class contains property Instance that:
Gets or sets the object instance on which the method is being executed.
as long as your method is not static you will get the object that is the this inside that method. Now you need to just cast it to BaseController as your property is public you will be able to access it.
if(args.Instance != null){
var baseController = (BaseController)args.Instance;
baseController._userSession
}
Although this is what you asked for I feel a need to remark that this approach limits your aspects usability to only instance methods of classes that inherit from BaseController. If you are able to create/retrieve form somewhere the session data in that parameterless constructor you can do it in aspect as well.

Dependency Injection in ASP.NET MVC

I've been using Dependency Injection in ASP.NET MVC the way I've explained in the below code, but I'm not sure if that is the right and standard way to do it. So I just wanna know if what I'm doing is wrong or if there is a better and more professional way to do it.
public interface IService {
public Boolean AddRecord(Object _Model);
}
public class Employee: IService {
DataBase Context = new DataBase();
public Boolean AddRecord(Object _Model) {
Context.Add((EmployeeModel) _Model);
return Context.SaveChanges() != 0;
}
}
public class DataController: Controller {
IService service;
public DataController(IService service) {
this.service = service;
}
public ActionResult AddRecord(Object _Model, String Caller) {
if (service.Add(_Model)) {
TempData["Result"] = "Data Added";
return RedirectToAction(Caller);
}
TempData["Result"] = "Please try again";
return View (Caller, _Model);
}
}
When I wanna use the controller with the DI, I do: (Is this the right way to consume the DataController)
public class TestController: Controller {
public ActionResult Index () {
return View();
}
public ActionResult TestIt (EmployeeModel _Model) {
DataController DC = new DataController(new Employee());
return DC.AddRecord(_Model, "../Test/TestIt");
}
}
You have the general concept of Dependency Injection / Inversion down. That is, you've understood that instead of this:
public class Example {
public void SomeFunc() {
var service = new Service();
service.DoStuff();
}
}
..you do this:
public class Example {
private readonly IService _service;
public Example(IService service) {
_service = service;
}
public void SomeFunc() {
_service.DoStuff();
}
}
.. and you supply the dependency manually via the calling code.. such as a Controller:
public HomeController : Controller {
[HttpGet]
public ActionResult Index() {
var example = new Example(new Service());
example.SomeFunc();
// .. the rest ..
}
}
So, the first part is Dependency Inversion. You have inverted the dependency chain from being top down to bottom up. The second part (the above code block) is Dependency Injection.
Notice in the above block of code that the Controller has no dependencies injected. This is where Inversion of Control comes in.
Inversion of Control is a pattern where code completely external to the currently running code decides how it functions. In this context, it means some external code - somewhere else - decides how to supply dependencies to your controller.
(Note, I am quite familiar with Ninject - so the below examples are using Ninject. There are plenty of other available DI/IoC containers available)
Ninject is a framework that can help with this (and many others). Ninject has an extension for ASP.NET MVC which automatically builds and supplies controller instances for you - plus your dependencies.
Without providing a full tutorial on using Ninject (which I will leave as an exercise to the OP to Google), the basics of it is this.
You declare a "module" with the configuration for your dependencies. Using the above examples, your module might look like this:
public class YourModule : NinjectModule {
public override void Load() {
Bind<IExample>().To<Example>().InRequestScope();
Bind<IService>().To<Service>().InRequestScope();
}
}
This will wire up all requests for an IExample to an Example, and IService to an instance of a Service. So your Controller would become:
public class HomeController : Controller {
private readonly IExample _example;
public HomeController(IExample example) {
_example = example;
}
[HttpGet]
public ActionResult Index() {
_example.SomeFunc();
// .. the rest ..
}
}
The container (in this case, Ninject) looks at your external code (the YourModule class) and determines what IExample should be. It sees that you've said it should be an instance of an Example class. Example also requires a dependency of type IService. So Ninject will again look at YourModule and determines that it should be an instance of Service. It continues to go down the object hierarchy until it completes the construction of the objects.
Hopefully that makes sense - it is definitely hard to explain these concepts in text.
I haven't viewed this video (I am running off of really really terrible WiFi hotspot while I wait for an internet connection!) so I can't verify it's quality, but a quick Google search turned this up for setting up Ninject and MVC: http://www.youtube.com/watch?v=w_MehI2qBTo
You would definitely benefit from Googling around some Inversion of Control and/or Ninject videos to understand what frameworks like it are for.
It is important to note too that frameworks like Ninject can also control scope. In the example above, I used InRequestScope against the bindings. This means that Ninject will instantiate the dependency at the start of the web request - and dispose of it afterward. This removes the need for you to worry about that.

WebApi Route with Nested Class

Is it possible to MapHttpRoute to a nested ApiController class? If yes, what RouteTemplate achieves it?
Example nested controller:
public class whatever
{
public class NestedController : ApiController
{
[HttpGet]
public object five()
{
return 5;
}
}
}
I've tried using
GET ApiRoute/whatever+nested/five
as typeof(whatever.NestedController) reports whatever+NestedController but I get
No type was found that matches the controller
It seems that the routing engine looks for concrete classes only. It doesn't matter which assembly they're in or which namespace they're in but they can't be nested in another class and they can't be abstract.
One benefit (although it's a stretch) is this is that you can "hide" controllers in a DLL and activate them in a Web App like this:
DLL:
public class Wrapper { public class MyController : ApiController { /*code goes here*/ } }
Web App:
public class MyController : Wrapper.MyController { }
All that said, I don't recommend it. It's best to use things as designed because you risk opening a security hole or making the application fragile to API updates.

Accessing Ninject objects from master view partial view

I am trying to access an object created by ninject within my layout view but I have no idea how to access them.
Here is a brief outline of what I have tried so far:-
Created by service and bound them:
public interface IService
{
void SomeMethod();
}
public class Service : IService
{
public void SomeMethod
{
}
}
Bind<IService>().To<Service>();
Created a static class and use the [Inject] attribute:
public static class MasterLayout
{
[Inject]
public static IService Service { private get; set; }
public static void CallSomeMethod();
{
Service.SomeMethod
}
}
Everytime I call MasterLayout.CallSomeMethod() from my master view or partial view, the Service field is always null.
Is this even possible or should I be creating a base Controller and getting other controllers to inherit from it where I can set those values to be used within the master view and partial views? Is there an even better way of achieving this?
Does Ninject work if used with contructor injection?
( see http://ninject.codeplex.com/wikipage?title=Injection%20Patterns )
Something like
IUnitOfWork UnitOfWork;
public AccountController(IUnitOfWork unitOfWork)
{
this.UnitOfWork = unitOfWork;
}
Have you checked here?
bind to property always return null
When you say "on every page", you mean "on every controller"?
If yes, i think you could create a BaseController class, and all the controllers should inherit from it. I'm using this method.
You have to create a custom controller factory to have Ninject create the controllers. Once you do, this will work. There is also probably an extension for this already.

Inheritance/Generics Basics. How to implement a code structure that's DRY

In an attempt to DRY up my code today i'd like to do the following. (I don't know if its the best way, but it seems better than to have an ever increasing code base where I continually need to update multiple methods if i want to change something across the whole site)
What i know about Inheritance is scary. As Iv'e never questioned any of the code/libraries that I use, and Iv'e never really attempted writing anything like this before, but I want to learn... Hoping this will be my day of enlightenment :P
To my question:
Say Iv'e got an add method (in all my controllers) like this:
public ActionResult Add(VM_Down_Time_Capture viewModel)
{
using (Down_Time_CaptureRepository repository = new Down_Time_CaptureRepository())
{
if (!ModelState.IsValid)
return ReturnValidationFailure(ViewData.ModelState.Values);
Down_Time_Capture model = new Down_Time_Capture();
model.InjectFrom(viewModel);
string mserMsg = repository.Add(model, User.Identity.Name);
if (!string.IsNullOrEmpty(mserMsg))
return ReturnCustomValidationFailure(Server.HtmlEncode(mserMsg));
repository.Save();
return Json("Added successfully.", JsonRequestBehavior.AllowGet);
}
}
And at the moment I've got the following as well.
Generated by T4 Templates/EF.
ViewModels, Repositories, (Standard) EF Models
I'm thinking I need a ModelSpecfic base controller for each page (can be done using T4), that inherits from a custom ControllerBase class that contains the basic CRUD functionality. That way i can have custom code per controller, and my code base will be cleaner & smaller & that wont get affected should i need to regenerate the base files
I don't quite understand how to implement something in the lines of what i need. What i understand so far is that ill need to have my repositories, and view models inherit from a base as well and somehow specify in [B] which ones I'm using... but as to how to do that i don't know
For example (and this is my best attempt at it, not my actual code, extremely hacky as I'm amazingly confused :S)
public class Down_Time_CaptureController : Down_Time_CaptureBase
{
//[A]
}
//Generated by T4
public class Down_Time_CaptureBase: ControllerBase
{
//[B]
public override EntityObject CreateNewModel()
{
return new Down_Time_Capture();
}
public override Base_Repository CreateNewRepository()
{
return new Down_Time_CaptureRepository();
}
public override Base_ViewModel CreateNewViewModel()
{
return new VM_Down_Time_Capture();
}
//how would i go about specifying which repository & model & view model to use
//although i expect it to be something to what i did here above
//and how would i go about calling the new generic add method (but in context of this controller)?
}
//coded once
public abstract class ControllerBase: Controller
{
//[C]
//make abstract so i have to override it
public abstract Base_Controller CreateNewModel();
public abstract Base_Controller CreateNewRepository();
public abstract Base_Controller CreateNewViewModel();
//I'm assuming my generified add method would go in here
public virtual ActionResult Add(Base_ViewModel viewModel)
{
using (Base_Repository repository = CreateRepository())
{
if (!ModelState.IsValid)
return ReturnValidationFailure(ViewData.ModelState.Values);
EntityObject model = CreateNewModel();
model.InjectFrom(viewModel);
string mserMsg = repository.Add(model, User.Identity.Name);
if (!string.IsNullOrEmpty(mserMsg))
return ReturnCustomValidationFailure(Server.HtmlEncode(mserMsg));
repository.Save();
return Json("Added successfully.", JsonRequestBehavior.AllowGet);
}
}
}
Here's a simple generic interpretation of what you are asking for:
// concrete controller implementation
public class Down_Time_CaptureController: ControllerBase<Down_Time_Capture, VM_Down_Time_Capture, Down_Time_CaptureRepository>
{
}
// generic controller base
public abstract class ControllerBase<TModel, TViewModel, TRepository>: Controller
where TModel : Base_Model, new()
where TViewModel : Base_ViewModel, new()
where TRepository : Base_Repository, new()
{
protected virtual TModel CreateNewModel()
{
return (TModel)Activator.CreateInstance<TModel>();
}
protected virtual TRepository CreateNewRepository()
{
return (TRepository)Activator.CreateInstance<TRepository>();
}
protected virtual TViewModel CreateNewViewModel()
{
return (TViewModel)Activator.CreateInstance<TViewModel>();
}
//I'm assuming my generified add method would go in here
public virtual ActionResult Add(TViewModel viewModel)
{
using (var repository = CreateRepository())
{
if (!ModelState.IsValid)
return ReturnValidationFailure(ViewData.ModelState.Values);
var model = CreateNewModel();
model.InjectFrom(viewModel);
string mserMsg = repository.Add(model, User.Identity.Name);
if (!string.IsNullOrEmpty(mserMsg))
return ReturnCustomValidationFailure(Server.HtmlEncode(mserMsg));
repository.Save();
return Json("Added successfully.", JsonRequestBehavior.AllowGet);
}
}
}
A few notes:
You will probably want to create interfaces for the three types (Model, ViewModel, Repository) and use those as the generic constraints.
You will probably want a generic Repository interface and base implementation (so you don't have to code each repository independently, and copy similar logic from one to the other).
Consider using an Inversion of Control container and dependency injection. Rather than have the controller, for example, handle creating an instance of a repository, make it a property and set it from the constructor. You can then use an IoC of your choice (like Ninject or Autofac) and register concrete implementations, and it will manage creating and the lifetime of both the dependencies and the controller itself.

Categories