Using Ninject with MVC3 controllers that are in external assemblies - asp.net-mvc

I have MVC3 controllers in external assemblies using MVC contrib's portable areas but I'm having a problem getting Ninject to inject the constructor dependencies.
The controller is found but I get an exception of "No parameterless constructor defined for this object". I can see that ninject's controller factory is being called in the call stack but for external assemblies it just does not pass my database session.
Why could this be?

Probably you should update Ninject. RegisterAllControllersIn is from a version that is outdated since a long time.

You need to register the controllers in the other assemblies using Ninject's RegisterAllControllersIn method.
This is my implementation in the applicationstarted method of global.asax:
foreach (var ass in BuildManager.GetReferencedAssemblies().Cast<Assembly>())
{
RegisterAllControllersIn(ass);
}

Related

Static factory method does not return object instance in MVC Controller

We are migrating from .aspx web application to MVC app.
Below is the problem while migrating:
I have a third party dll which contains static factory method to return instance by given Interface name.
Controller code:
IBus objBus = (IBus) ObjectFactory.GetInstance("IBus") as IBus;
Here, ObjectFactory is from third party dll with definition as below (no more code details are available on GetInstance method).
public class ObjectFactory
{
public ObjectFactory();
public static object GetInstance(string interfaceName);
}
GetInstance method works perfectly in .aspx application - objBus is created successfully.
But the same line (Controller code) when executed in MVC controller returns objBus as null.
Please suggest what could be the problem.
I guess it may be due to difference in architecture and/or page life cyle of .aspx and mvc apps.
Any suggestions on the problem are greatly appreciated.
I think you should reach out to your third party DLL provider and ask for documentation on how to work with ASP.NET MVC.
If I was you I would think about dropping that DLL using Unity for you dependency injection for an MVC Project. All you need to do is in the Application_Start method in the Global.asax use the UnityConfig and DependecyResolver to inject you instances of class in to any of your controller methods.
If you need details check out these great articles.
http://netmvc.blogspot.com/2012/04/dependency-injection-in-aspnet-mvc-4.html
http://dotnetslackers.com/articles/aspnet/Using-Microsoft-Unity-in-ASP-NET-MVC.aspx
http://www.codeproject.com/Articles/99361/How-To-Use-Unity-Container-In-ASP-NET-MVC-Framewor

MVC5, WebAPI2 and Ninject Parameterless constructor error

So I have the exact opposite problem as MVC5, Web API 2 and Ninject
I have a new MVC5/WebAPI2 project, that has both "Controller"s and "ApiControllers".
I'm using the latest unstable version of Ninject.Web.WebAPI with no code changes to NinjectDependencyResolve.cs and Ninject.WebCommom.cs (besides binding my dependency) the ApiController's constructor injection works. However, when I call a MVC Controller I get:
No parameterless constructor defined for this object.
The issue is you need a Dependency Resolver for both MVC and WebAPI. Depending on which set of Ninject libraries you use, you only get one of those wired in for you.
i.e. if you use the Ninject.Web.WebAPI library you will need to manually set the MVC resolver:
System.Web.Mvc.DependencyResolver.SetResolver(new NinjectResolver(kernel));
(I did this in NinjectWebCommon.cs CreateKernel())
Your Ninject resolver can inherit the interface for both WebAPI and MVC:
public class NinjectResolver : NinjectScope,
System.Web.Http.Dependencies.IDependencyResolver,
System.Web.Mvc.IDependencyResolver

Cannot initialize variables in constructor that's using dependency injection

I have a constructor that's getting its dependencies from a Dependency Injection framework (Autofac). The problem is I can not do anything else in the constructor except getting those dependencies, if I write any statement inside the constructor other than those dependency assignments, I get the following error:-
No parameter less constructor is defined for this object
I have to comment the assignment of readonly string shown below for this to work:-
public RelationshipController(ICustomerService customerService,)
{
this.customerService = customerService;
//someReadonlyString = "abcd";
}
Can somebody tell me, What's happening?
When the requested service (in this case, ICustomerService) cannot be found in the container, Autofac will move on to look for a default (a.ka. the parameterless) constructor. You obviously have no default constructor, thus Autofac bails out with an exception.
My guess is that the real error here is in the registration code for the ICustomerService interface.
I see a RelationshipController which probably means that you are using ASP.NET MVC. You probably didn't register Autofac correctly in MVC. In that case, MVC will not use Aufofac and can only work with default constructors.

How does ninject doing Dependency injection in Asp.net MVC

i studying by the book Pro asp.net mvc2 by apress, In the book the author uses ninject for dependency injection.
He inherits the default control factory :
public class NinjectControllerFactory : DefaultControllerFactory
and then overrides : GetControllerInstance
I have 2 questions.
how does the DefaultControllerFactory knows what controller to load ? i assume he uses the route table and then loads it with reflection. am i correct ?
and how the ninject knows to do it, the only line i wrote is :
private IKernel kernel = new StandardKernel();
return (IController)kernel.Get(controllerType);
Ninject can't possibly know about my route table and which control he should load ..
so how does he knows ?
ps.
i use the regular ninject, not some specific version that created for MVC (which i believe they have on their website also)
this is for mvc3 but a good article about ninject and mvc.
http://dotnetslackers.com/articles/aspnet/Experience-ASP-NET-MVC-3-Beta-the-New-Dependency-Injection-Support-Part1.aspx
NinjectControllerFactory.GetControllerInstance gets called by MVC. This means it is MVC that evaluates which controller type is required to process a request and it get it from the routing table.
If you want to use this I recommend using https://github.com/ninject/ninject.web.mvc It will save you time and work as it is maintained together with Ninject. Otherwise you will have to update to new Ninject versions yourself.

How does Ninject create controller in ASP.NET MVC?

This may be stupid question, but I am looking at Ninject sources and don't see NInject registering its own controller factory. I also don't see any IControllerFactory class in Ninject.Web.Mvc assembly. Am I missing something? How does Ninject create controller and inject parameters into constructor?
Lets say we are looking for "/Task/Index".
Ninject MVC applications use now DefaultControllerFactory, the same as non-Ninject applications.
DefaultControllerFactory finds type for controller (TaskController).
DefaultControllerFactory has internal class called DefaultControllerActivator. DefaultControllerActivator has method called Create, which returns controller instance. DefaultControllerFactory asks DefaultControllerActivator for TaskController type instance.
DefaultControllerActivator.Create uses IDependencyResolver. This is where Ninject comes in. Since Ninject implements its own resolver and sets it at the start of application, he gets request for TaskController instance.
The rest is easy. Ninject finds constructor for this type, injects parameters, returns controller instance.
MVC3 now recommends the usage of the IDependencyResolver interface instead of the good old IControllerFactory when dealing with DI. You can look at more details of this interface here.
This is the new Ninject class responsible for injecting the dependencies.
Since controllers are concrete types, Ninject will do self bind. Below is a snippet from ninject.complex.com
Bear in mind that only concrete types can be self-bound; abstract
types and interfaces won't work. Also, if you request an instance of a
type that can be self-bound, and there are no bindings defined for the
type, Ninject will automatically create an implicit self-binding. It's
up to you whether you want to define your bindings explicitly, or let
Ninject figure it out.
If you do need to inject parameters into the constructor. You can create a class inherits from INinjectModule and do the binding there.

Resources