Share a Kernel between WebAPI and MVC - asp.net-mvc-4

I've got a simple MVC4 site which uses ASP.NET webAPI and also MVC pages.
I'd like to use Ninject DI for both controller types but I'm wondering how this can be done?
I've got Ninject DI working for WebAPI, but now not sure how to share the same Kernel elegantly.
Should I be using some sort of Kernel singleton which both Dependency Resolvers can refer to?
Anyone had any experience with this?
Cheers.

You should use the same IKernel instance for a single application-level composition root, may be WebApi or MVC controllers.
If you are using Ninject.MVC3 package:
When the kernel is initialized in NinjectWebCommon.cs inside your App_Start folder, you already have access to it. For MVC controllers, you don't need to do anything else for Ninject DI to work.
But for WebAPI controllers, you need to use a DependencyResolver to inject dependencies into your controllers. Using this implementation for this resolver, you then set it to be the resolver for all your WebAPI controllers like this:
Bind the NinjectDependencyResolver to self (optional), inside RegisterServices in NinjectWebCommon.cs:
kernel.Bind<NinjectDependencyResolver>().ToSelf();
Set the WepAPI configuration to use your Resolver, usually inside WebApiConfig.cs:
public static void Register(HttpConfiguration config)
{
//Other initialization code
config.DependencyResolver = (new Bootstrapper()).Kernel.Get<NinjectDependencyResolver>();
}
This will fit your scenario for all controllers sharing the same IKernel.
Hope that helps!

Yes, you are right. There should be one kernel/ container for an application, because this will eleminate possible mistakes in the future.In case of multiple kernels, you may register an interface in a kernel, and then try to resolve it using another kernel, and the program crashes.Only After spending time debugging, you find out what was wrong,etc.
In addition, using a single kernel, you wouldn't have to register a same implementation multiple times.

Related

Issue when configuring Hangfire in ASP.NET app

I'm attempting to wire up Hangfire in my ASP.NET application (not Core) using the Global.asax.cs route explained in their documentation. However, none of their extensions methods on GlobalConfiguration.Configuration seem to be working for me. It appears, for one example, that SetDataCompatibiltyLevel() method extends Hangfire.IGlobalConfiguration, which my GlobalConfiguration.Configuration does not inherit from. I even backed off a few versions of Hangfire and it doesn't seem to make a difference. When I attempt to access the extensions method directly, I get this:
Prefix GlobalConfiguration class with the Hangfire namespace – System.Web.Http namespace defines its own GlobalConfiguration class, so you get a conflict. And that another class is referenced, most likely because you have the System.Web.Http namespace included in the beginning of the file.
Hangfire.GlobalConfiguration.Configuration
.SetDataCompatibilityLevel(CompatibiltyLevel.Version_170);
You can also combine all the calls to the GlobalConfiguration class in a single chain:
Hangfire.GlobalConfiguration.Configuration
.SetDataCompatibilityLevel(CompatibiltyLevel.Version_170)
.UseXXX()
.UseYYYStorage();

How to inject UrlHelper in Web API 2 using StructureMap.WebApi2 nuget package

I am using StructureMap.WebApi2 nuget package for Web API 2 project for managing the depedency injection.
The Web API controllers use constructor injection to inject a UrlHelper dependency which should be resolved by StructureMap Ioc.
I am trying the following approach to set the UrlHelper for web api controller:
public class FooController : ApiController
{
private UrlHelper _UrlHelper;
public ModelFactory(HttpRequestMessage request)
{
_UrlHelper = new UrlHelper(request);
}
}
But with the above code I am getting the following error:
No default Instance is registered and cannot be automatically determined for type 'System.Net.Http.HttpMethod' There is no configuration specified for System.Net.Http.HttpMethod
Can anyone suggest me the best possible ways to resolve the above issue?
Your problem is that StructureMap tries to resolve the greediest constructor first, in this instance taking a look at the source code for HttpRequestMessage reveals the following constructors:
public HttpRequestMessage(HttpMethod method, string requestUri);
public HttpRequestMessage(HttpMethod method, Uri requestUri);
This is where your HttpMethod issue is coming from. StructureMap tries to create an instance of HttpRequestMessage but has no idea how to resolve the method and requestUri dependencies.
In this instance you need to manually configure your dependency within your StructureMap configuration so it knows how to create an instance of HttpRequestMessage like so:
this.For<HttpRequestMessage>().Use(new HttpRequestMessage());
Alternatively, to create instances of overloaded constructors then you'll need to manually resolve the overloaded dependencies (I would recommend using a factory for this in order to keep your SM configuration nice and clean. Here is an example of how you can do this).

Calling WebApi Controller action, causes Inheritance security rules violated HostedHttpRouteData.get_Route(

I have a .Net Mvc4 project, I've added a WebApi Controller and a basic action in for an ajax call.
When I call the method I get:
Inheritance security rules violated while overriding member:
'System.Web.Http.WebHost.Routing.HostedHttpRouteData.get_Route()'.
Security accessibility of the overriding method must match the
security accessibility of the method being overriden.
I haven't made any custom modifications or set up anything for web Api to work (was I supposed to?)
I noticed the DefaultApi route is in my routeConfig.
I'm also using Unity Mvc4 & Unity Web Api packages, (which I've disabled to test if it was causing the issue but doesn't seem to be).
My controller is TestController
action:
public bool ClearAwaitingNotifications()
{}
& ajax call is going to: api/test/clearawaitingnotifications
How can I fix this?
My exception occured when hitting controller because:
WebApiConfig.Register(GlobalConfiguration.Configuration);
was never called, although the route existed inside my Routeconfig.cs. I think this occurred because I installed my Mvc4 project using a template, which installs some WebApi stuff and it is all a bit old. I then added this line into Global.ascx and received the same security warning but for this line in Global.ascx.
https://stackoverflow.com/a/18713412/314963 then helped me resolve the issue, and now everything is working. In short, it is because of installing Mvc project with a template, or because one of the libraries in webapi 4 was outdated.

Is it possible to test Portlet Controllers using Springs MockMvc?

You can test your "normal" Spring MVC Controllers using the MockMvc class like so:
mockMvc
.perform(get("/my/fine/path"))
.andExpect(status().isOk());
From the Spring Reference on Handler Mappings:
Since there is really no such thing as a URL within a Portlet, we must use other mechanisms to control mappings. The two most common are the portlet mode and a request parameter, but anything available to the portlet request can be used in a custom handler mapping.
Is MockMvc only for "normal" Controllers or is there a way of using it when testing Portlet Controllers?
Checkout spring-test-portlet-mvc (https://github.com/markusf/spring-test-portlet-mvc), which exposes the features of MockMvc to the Portal context!

Autobinding in MVC4 WebApi with Ninject.Extensions.Conventions

In my MVC4 app I'm using Ninject.Extensions.Conventions to autobind all itnerfaces with their implementation using default mechanism:
kernel.Bind(x => x
.FromAssembliesMatching("*")
.SelectAllClasses()
.BindDefaultInterface());
This works great for regular controllers, but doesn't for WebApi controllers. What do I need to change/add?
Ok, I resolved the issue by following this article:
http://www.peterprovost.org/blog/2012/06/19/adding-ninject-to-web-api/
In short: I created my own dependency resolver (as per article) and assigned it to GlobalConfiguration.Configuration.DependencyResolver as suggested by nemesv
There are already a many examples on how to integrate NInject with Web API through the web, using:
DependencyResolver
On ASP.NET website is shown standart way of integration of any DI/IoC with Web API:
http://www.asp.net/web-api/overview/extensibility/using-the-web-api-dependency-resolver
IDependencyResolver.
WebApiContrib project shows how to do it with IDependencyResolver
https://github.com/WebApiContrib/WebApiContrib.IoC.Ninject
Please post more information about your implementation of these resolvers, to be more specific in answer.