Coder Social home page Coder Social logo

ninject.web.mvc's Introduction

Ninject.Web.Mvc

Build status NuGet Version NuGet Downloads

This extension allows integration between the Ninject and ASP.NET MVC projects. To use it, just make your HttpApplication (typically in Global.asax.cs) extend NinjectHttpApplication:

public class YourWebApplication : NinjectHttpApplication
{
  public override void OnApplicationStarted()
  {
    // This is only needed in MVC1
    RegisterAllControllersIn("Some.Assembly.Name");
  }

  public override IKernel CreateKernel()
  {
    return new StandardKernel(new SomeModule(), new SomeOtherModule(), ...);
    
    // OR, to automatically load modules:
    
    var kernel = new StandardKernel();
    kernel.AutoLoadModules("~/bin");
    return kernel;
  }
}

Once you do this, your controllers will be activated via Ninject, meaning you can expose dependencies on their constructors (or properties, or methods) to request injections.

ninject.web.mvc's People

Contributors

dependabot[bot] avatar iappert avatar idavis avatar joshclose avatar petebacondarwin avatar remogloor avatar scott-xu avatar silentbobbert avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ninject.web.mvc's Issues

Controller level filter stops global filter from executing (MVC3, 2.2+)

A global filter is not executing when a controller contains a controller level filter.

Tried with ninject 2.3.0.6 and 2.2.1.1

To reproduce

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class AlphaAttribute : Attribute {}

    public class FilterAlpha : IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext filterContext) {}

        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            filterContext.Controller.ViewData["alpha"] = "here";
        }
    }

    public class FilterBeta : IActionFilter
    {
        public void OnActionExecuting(ActionExecutingContext filterContext) {}

        public void OnActionExecuted(ActionExecutedContext filterContext)
        {
            filterContext.Controller.ViewData["beta"] = "here";
        }
    }

    [Alpha]
    public class WithController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }

    public class WithoutController : Controller
    {
        public ActionResult Index()
        {
            return View();
        }
    }

Registration

            kernel.BindFilter<FilterAlpha>(FilterScope.Controller, 0)
                .WhenControllerHas<AlphaAttribute>();

            kernel.BindFilter<FilterBeta>(FilterScope.Global, 0);

Views

<p>Alpha? @ViewData["alpha"]</p>
<p>Beta? @ViewData["beta"]</p>

Example project can be found here

Ninject.Mvc5 does not work with mono

Wrongly posted it in ninject/Ninject#172
I have a problem well articulated here [1]. In summary is injection does not occur and Accessing controller from URL throws Error:

System.MissingMethodException
Default constructor not found for type OnlineShopping.WebUI.Controllers.ProductController

Description: HTTP 500.Error processing request.

Details: Non-web exception. Exception origin (name of application or object): mscorlib.
Exception stack trace:
  at System.Activator.CreateInstance (System.Type type, Boolean nonPublic) [0x000a9] in <filename unknown>:0 
  at System.Activator.CreateInstance (System.Type type) [0x00000] in <filename unknown>:0 
  at System.Web.Mvc.DefaultControllerFactory+DefaultControllerActivator.Create (System.Web.Routing.RequestContext requestContext, System.Type controllerType) [0x00015] in <filename unknown>:0 
Version Information: 4.0.1 (tarball Tue May 12 15:39:23 UTC 2015); ASP.NET Version: 4.0.30319.17020

Here are mono information

 mono --version
Mono JIT compiler version 4.0.1 (tarball Tue May 12 15:39:23 UTC 2015)
Copyright (C) 2002-2014 Novell, Inc, Xamarin Inc and Contributors. www.mono-project.com
    TLS:           __thread
    SIGSEGV:       altstack
    Notifications: epoll
    Architecture:  amd64
    Disabled:      none
    Misc:          softdebug 
    LLVM:          supported, not enabled.
    GC:            sgen

My OS is Ubuntu 14.04 if that is of any help

[1] http://stackoverflow.com/questions/30590663/ninject-mvc5-does-not-work-with-mono/30594686#30594686

Sequence contains no elements - Bootstrapper

System.Linq.Enumerable.Single(IEnumerable`1 source) +379
Ninject.Web.Mvc.NinjectMvcHttpApplicationPlugin.Start() in c:\Projects\Ninject\ninject.web.mvc\mvc3\src\Ninject.Web.Mvc\NinjectMvcHttpApplicationPlugin.cs:53

I cannot seem to get this up and running. I've followed the instructions to the letter..

nothing changed in global I'm using the App_Start folder

[assembly: WebActivator.PreApplicationStartMethod(typeof(EFWebApp.Web.App_Start.NinjectWebCommon), "Start")]
[assembly: WebActivator.ApplicationShutdownMethodAttribute(typeof(EFWebApp.Web.App_Start.NinjectWebCommon), "Stop")]

namespace EFWebApp.Web.App_Start
{
using System;
using System.Web;

using Microsoft.Web.Infrastructure.DynamicModuleHelper;

using Ninject;
using Ninject.Web.Common;

public static class NinjectWebCommon
{
    private static readonly Bootstrapper bootstrapper = new Bootstrapper();

    /// <summary>
    /// Starts the application
    /// </summary>
    public static void Start()
    {
        DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
        DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));
        bootstrapper.Initialize(CreateKernel);
    }

    /// <summary>
    /// Stops the application.
    /// </summary>
    public static void Stop()
    {
        bootstrapper.ShutDown();
    }

    /// <summary>
    /// Creates the kernel that will manage your application.
    /// </summary>
    /// <returns>The created kernel.</returns>
    private static IKernel CreateKernel()
    {
        var kernel = new StandardKernel();
        kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
        kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

        RegisterServices(kernel);
        return kernel;
    }

    /// <summary>
    /// Load your modules or register your services here!
    /// </summary>
    /// <param name="kernel">The kernel.</param>
    private static void RegisterServices(IKernel kernel)
    {
        kernel.Load<EFWebNinjectModule>();
    }
}

}

How to Inject EF Core in MVC .Net Framework 4.6.1

I am having trouble injecting EF Core into my MVC Web application (framework 4.6.1). I have a SO question here but to summerize:
I am binding the DbContext to itself in transient scope but it seems that the context instance is being reused and then it fails because EF has closed the connections. In the controller method I make a call to the db in one repository which works and then I make a call to the db in a different repository which fails and throws an exception.

No database provider has been configured for this DbContext. A provider can be configured by overriding the DbContext.OnConfiguring method or by using AddDbContext on the application service provider. If AddDbContext is used, then also ensure that your DbContext type accepts a DbContextOptions object in its constructor and passes it to the base constructor for DbContext.

Code examples are in the SO question.

Add ActionResult invoker

I noticed that Ninject.Web.Mvc has an ActionFilter invoker, to inject dependencies into an ActionFilter. Is it possible to do the same for ActionResults?

Strong Name

Would it be possible to sign this with a strong name with the same key used for Ninject core?

Error activating IFilterProvider using binding from IFilterProvider to NinjectFilterAttributeFilterProvider

A cyclical dependency was detected between the constructors of two services. Activation path: 1) Request for IFilterProvider

I keep getting this in a production server after a few hours of flawless execution. I don't see any other exceptions in the elmah logs and my current guess is that the server is reloading/restarting the app somehow and this leads to the exceptions. Of course, once those appear, the whole app is unusable.

I'm using Ninject 2.2.0.0 and Ninject.Web.Mvc 2.2.0.3 and extend NinjectHttpApplication in my Global.asax.cs (Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.1; ASP.MVC 3)

Here's the full trace

[ActivationException: Error activating IFilterProvider using binding from IFilterProvider to NinjectFilterAttributeFilterProvider
A cyclical dependency was detected between the constructors of two services.

Activation path:
  1) Request for IFilterProvider

Suggestions:
  1) Ensure that you have not declared a dependency for IFilterProvider on any implementations of the service.
  2) Consider combining the services into a single one to remove the cycle.
  3) Use property injection instead of constructor injection, and implement IInitializable
     if you need initialization logic to be run after property values have been injected.
]
   Ninject.Activation.Context.Resolve() in d:\BuildAgent-01\work\b68efe9aafe8875e\src\Ninject\Activation\Context.cs:148
   Ninject.KernelBase.b__7(IContext context) in d:\BuildAgent-01\work\b68efe9aafe8875e\src\Ninject\KernelBase.cs:375
   System.Linq.<>c__DisplayClass12`3.b__11(TSource x) +32
   System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +151
   System.Linq.d__b1`1.MoveNext() +92
   System.Linq.d__71`1.MoveNext() +117
   System.Linq.d__14`2.MoveNext() +399
   System.Linq.Buffer`1..ctor(IEnumerable`1 source) +217
   System.Linq.d__0.MoveNext() +96
   System.Linq.Buffer`1..ctor(IEnumerable`1 source) +217
   System.Linq.d__a0`1.MoveNext() +93
   System.Web.Mvc.d__b.MoveNext() +131
   System.Linq.Buffer`1..ctor(IEnumerable`1 source) +217
   System.Linq.d__a0`1.MoveNext() +93
   System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +87
   System.Linq.d__aa`1.MoveNext() +88
   System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection) +395
   System.Web.Mvc.FilterInfo..ctor(IEnumerable`1 filters) +248
   System.Web.Mvc.ControllerActionInvoker.GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor) +47
   System.Web.Mvc.ControllerActionInvoker.InvokeAction(ControllerContext controllerContext, String actionName) +128
   System.Web.Mvc.Controller.ExecuteCore() +115
   System.Web.Mvc.ControllerBase.Execute(RequestContext requestContext) +94
   System.Web.Mvc.ControllerBase.System.Web.Mvc.IController.Execute(RequestContext requestContext) +10
   System.Web.Mvc.<>c__DisplayClassb.b__5() +37
   System.Web.Mvc.Async.<>c__DisplayClass1.b__0() +21
   System.Web.Mvc.Async.<>c__DisplayClass8`1.b__7(IAsyncResult _) +12
   System.Web.Mvc.Async.WrappedAsyncResult`1.End() +55
   System.Web.Mvc.<>c__DisplayClasse.b__d() +31
   System.Web.Mvc.SecurityUtil.b__0(Action f) +7
   System.Web.Mvc.SecurityUtil.ProcessInApplicationTrust(Action action) +23
   System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult) +59
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result) +9
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +8841105
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +184

Asynchronous action methods not working

NinjectControllerFactory.CreateActionInvoker creates a ControllerActionInvoker-Subclass (Ninject.Web.Mvc.NinjectActionInvoker). But for asynchronous action methods to work correctly an AsyncControllerActionInvoker-Subclass is needed.

I have a solution that works for me - but it feels "not DRY". I created an AsyncNinjectActionInvoker that inherits from AsyncControllerActionInvoker - with the same GetFilters-Method as the NinjectActionInvoker.

Presumably it would be better to make NinjectActionInvoker inherit from AsyncControllerActionInvoker - but I was not sure whether that brings some overhead to all synchronous action methods.

UPDATE: Meanwhile I decided to undo my last changes and just change the NinjectActionInvoker to inherit from AsyncControllerActionInvoker.

Sequence contains no elements

I know there is issue number 24 related to this. I am still having trouble in solving this issue. I installed ninject.mvc3 package which installs ninject and ninject.web.common packages. No modification was made in global.asax (as suggested in official documentation).

App_Start/NinjectWebCommon.cs's RegisterServices method has the bind statement after loading the kernel. I am getting this error with this stack trace.

[InvalidOperationException: Sequence contains no elements]
System.Linq.Enumerable.Single(IEnumerable1 source) +379 Ninject.Web.Mvc.NinjectMvcHttpApplicationPlugin.Start() in c:\Projects\Ninject\ninject.web.mvc\mvc3\src\Ninject.Web.Mvc\NinjectMvcHttpApplicationPlugin.cs:53 Ninject.Infrastructure.Language.ExtensionsForIEnumerableOfT.Map(IEnumerable1 series, Action1 action) in c:\Projects\Ninject\ninject\src\Ninject\Infrastructure\Language\ExtensionsForIEnumerableOfT.cs:32 Ninject.Web.Common.Bootstrapper.Initialize(Func1 createKernelCallback) in c:\Projects\Ninject\Ninject.Web.Common\src\Ninject.Web.Common\Bootstrapper.cs:53
Ninject.Web.Common.NinjectHttpApplication.Application_Start() in c:\Projects\Ninject\Ninject.Web.Common\src\Ninject.Web.Common\NinjectHttpApplication.cs:81

[HttpException (0x80004005): Sequence contains no elements]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +12864673
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +175
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +304
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +404
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +475

[HttpException (0x80004005): Sequence contains no elements]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +12881540
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +159
System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +12722601

What step am I still missing?

MVC4 and MVC 4 Web API

Are there any rough timescales for a webapi implementation for ninject? We are currently considering implementing ninject on a new project and in order to assess if ninject can be included in a suitable timeframe it would be helpful to know if it is planned or if there is a workaround. The Wiki link implies this functionality is not yet present.

FilterBinding Request/Explanation

Is there a reason why the fluent filter binding interface does not support the following syntax? (Reworded: I'm I being stupid by wishing the following was supported?)

kernel.BindFilter<CustomAuthorizationFilter>(FilterScope.Global, 0).UnlessActionMethodHas<AllowAnonymousAttribute>();

type or assembly bootstrapper is unknown

i have an mvc site thats used ninject (not sure which version) via the global.asax and the application start method.
i saw the new ninject packages in nuget and so i installed those.
everything looks great, it adds all the files, but it won't compile
the app_start\NinjectMVC3.cs has a type "bootstrapper" that is unknown.
i'm missing a reference or something, but i don't know where to start looking.
the project is referencing ninject and ninject.mvc.

Filters not firing for MVC Area

Hi

Been working on this for two days now without luck. Does anyone know why the filters (in this case the UnitOfWorkFilter) are not firing for the controllers within an MVC Area. Everything else seems to be working ok.

Binding in: public override void Load()

Kernel.BindFilter<UnitOfWorkFilter>(FilterScope.Action, 0);

Ninject is starting using PreApplicationStartMethod rather than extending HttpApplication. Could this be the cause?

[assembly: WebActivator.PreApplicationStartMethod(typeof(NinjectWebCommon), "Start")]
[assembly: WebActivator.ApplicationShutdownMethod(typeof(NinjectWebCommon), "Stop")]

namespace FreeSurvey.Web.Mvc
{
    public static class NinjectWebCommon
    {
        private static readonly Bootstrapper Bootstrapper = new Bootstrapper();

        /// <summary>
        /// Starts the application
        /// </summary>
        public static void Start()
        {
            DynamicModuleUtility.RegisterModule(typeof(OnePerRequestHttpModule));
            DynamicModuleUtility.RegisterModule(typeof(NinjectHttpModule));

            Bootstrapper.Initialize(CreateKernel);

            GlobalConfiguration.Configuration.DependencyResolver = new NinjectResolver(Bootstrapper.Kernel);
            GlobalHost.DependencyResolver = new SignalRNinjectResolver(Bootstrapper.Kernel);
            ControllerBuilder.Current.SetControllerFactory(new NinjectControllerFactory(Bootstrapper.Kernel));
        }

Need to raise 404 for a not found controller in MVC 2.0 code

protected override IController GetControllerInstance(RequestContext requestContext, Type controllerType)
{
        if (controllerType == null)
            throw new HttpException(
                404, String.Format(
                         "The controller for path '{0}' could not be found " +
                         "or it does not implement IController.",
                         requestContext.HttpContext.Request.Path));

var controller = Kernel.TryGet(controllerType) as IController;
...

Asp.Net MVC 4 Web Api Filters

The BindFilter is currently set up to accept System.Web.Mvc filters.

In Asp.Net MVC 4 the Web Api's filters are System.Web.Http.Filters so they can't be used.

NinjectWebCommon.cs do not appear

Ninject.MVC5 installing fine , but not creating the required NinjectWebCommon.cs files .. VS 2015 enterprise version with 4.7 framework

Multiple filter of same type on Action method

I know it is supported but we have to repeat binding for filter every time we repeat filter on action method. Is there any reason that it is not supported to bind all at once.

For example:- if we have filter "A" and we want to apply it to one of action method "B" 2 times then we need to bind it twice via ninject.

thx
Balwinder

No longer injecting constructor parameters in Controllers in MVC 5

I've just upgraded to MVC 5 RTM, and am experiencing issues with Ninject. I've not modified any code and am now experiencing the following exception:

[MissingMethodException: No parameterless constructor defined for this object.]
   System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
   System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +113
   System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache, StackCrawlMark& stackMark) +232
   System.Activator.CreateInstance(Type type, Boolean nonPublic) +83
   System.Activator.CreateInstance(Type type) +66
   System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +110

[InvalidOperationException: An error occurred when trying to create a controller of type 'Web.Controllers.HomeController'. Make sure that the controller has a parameterless public constructor.]
   System.Web.Mvc.DefaultControllerActivator.Create(RequestContext requestContext, Type controllerType) +247
   System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +438
   System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +226
   System.Web.Mvc.MvcHandler.ProcessRequestInit(HttpContextBase httpContext, IController& controller, IControllerFactory& factory) +326
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContextBase httpContext, AsyncCallback callback, Object state) +157
   System.Web.Mvc.MvcHandler.BeginProcessRequest(HttpContext httpContext, AsyncCallback callback, Object state) +88
   System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.BeginProcessRequest(HttpContext context, AsyncCallback cb, Object extraData) +50
   System.Web.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +301
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Any suggestions on what may be going on?

You can't inject attributes

NinjectFilterAttributeFilterProvider is nonsense: you cannot inject dependencies into attributes.
There is exactly one instance of attribute per attribute application per appdomain, which means you will inject dependencies into the same instance over and over again, on every request.

This is fine when those dependencies are globally scoped, but not so fine when they are, say, request-scoped, which is a very common case. Even less fine if you happen to handle multiple requests at the same time, which is not just common case - it's the ONLY case. And in that case, you get yourself weird race conditions.

OnePerRequestHttpModule does not perform its cleanup work

When installing the latest nuget package (3.2.1), I noticed that disposable components in request scope were no longer properly cleaned up (Dispose() not called at request end). When downgrading to 3.2.0, all is fine. After looking at the code, it seems that MvcModule no longer inherits from GlobalKernelRegistrationModule, but directly from NinjectModule. Consequently, the kernel instance is no longer in GlobalKernelRegistration, and the MapKernels call in OnePerRequestHttpModule has no effect.
Am I missing something (some config, or module to load)? Or is it an issue in the generated code when installing the nuget package? Or possibly a bug?

MVC4 Medium Trust issue

I have hosted my website with Speedhost.in. Recently they changed the default setting for all web-apps from full to medium. I am getting a Security Exception since then. My hosting company has restricted overriding of trustlevel policy and so I cannot change the trustlevel to full again.

The security exception I am getting is more of a general exception and I am unable to think of a way to fix this. How should I decide which dll is asking for the restricted permission?

http://stackoverflow.com/questions/28381074/shared-windows-hosting-asp-net-getting-security-exception-when-trustlevel-chan
dxvlv

Please Update Web Activator Dependency

Hi I have been working with the creator of WebActivator closely for a new issue that arose with update to .net 4.5 using MVC. We have patched a work around in WebActivator 2.0.2, but ninject this requires 1.5.x

Can you please update ninject to use the latest WebActivator

Help: How I can change dependency based on Area In Asp.net MVC

I am very new. Just know how to use Ninject MVC3 extension. I want to change dependency based on Area. I have several DBContext for my application. I want to inject them based on Area.

Need your help. How i can achieve this. I know how to Rebind the dependency but where i have to configure this so that it rebinds dependency based on Area.

I am sorry if I posted it on wrong place.
Waiting for your help.

Dependency Injection Outside Controller (MVC 4 Web API)

I have an ApiController with the following constructor signature:

public BlazrController(BlazrDBContext dbContext, IAuthProvider authProvider, ILogger logger) { ... }

My bindings:

kernel.Bind<BlazrDBContext>().ToSelf().InRequestScope();
kernel.Bind<IHasher>().To<PasswordHasher>().InRequestScope();
kernel.Bind<IIPContextProvider>().To<DefaultIPContextProvider>().InRequestScope();
kernel.Bind<ILocationContextProvider>().To<DefaultLocationContextProvider>().InRequestScope();
kernel.Bind<ILogger>().To<FileLogger>().InRequestScope();
kernel.Bind<IAuthProvider>().To<BlazrAuthProvider>().InRequestScope();

And the IAuthProvider implementation (BlazrAuthProvider) has a constructor with signature:

public BlazrAuthProvider(BlazrDBContext dbcontext, IHasher hasher) {....}

When I run my application and navigate to a route under the ApiController above, I get the whole "No default constructor" error. I have removed the injected parameters from the constructors as to narrow down which one was causing the problem - and it was the IHasher under the BlazrAuthprovider. If I remove that from the constructor, it loads just fine.

I implemented a NinjectDependencyResolver (IDependencyResolver) as others have suggested but still can't get this to work. Am I missing something?

Also worth noting: the Controller is under it's own Web API Project and the other classes/interfaces are under a Class Library Project in the same solution.

Parameter name to WithConstructorArgumentFromControllerAttribute is not enforced

Given the following code

this.BindFilter<FooFilter>(FilterScope.Controller, order: 0)
    .WhenControllerHas<FooAttribute>()
    .WithConstructorArgumentFromControllerAttribute<FooAttribute>(parameterName, someLambda);

I've found that the parameterName passed in must not be null or empty, but as long as a type matches, it will succeed. My expectation was that it would fail to bind if it couldn't find a parameter with the proper name AND type provided. Ninject seems to prefer Constructors with more dependencies, so it's possible you could attempt to override a parameter of one constructor with less parameters but will instead override the other that may contain a non-matching name.

For example:

public class FooFilter : IFooFilter
{
    public FooFilter(IFoo f) { .. }
    public FooFilter(IFoo foo, IBar bar) { .. }
}

Specifying a constructor parameter name of "f" will still prefer the latter constructor. The parameter name seems to be ignored.

Different behaviour during debug with visual studio 2012

Hi, I encountered a strange problem when using ninject in mvc4 project.
Simply speaking, I want inject multiple IxxxRepository into controller, each IRepository constructed with IUnitOfWork implementation. IUnitOfWork implementation using InThreadScope object scope. But the problem is, everything runs as expected without vs debug, but when using VS debug and hit breakpoint in an Action, seems IxxxRepository's UnitOfWork are different.
Does VS debug will cause Ninject inject different instance into one controller although that object register with InThreadScope?
It strange because it just happened with VS debug mode....Can anybody helps?
Update: InRequestScope has same issue with VS 2012 debug.

MVC 3 Medium Trust

Having an issue getting Ninject.Web.Mvc to work in Medium Trust. "UseReflectionBasedInjection" is set to true as a parameter during the creation of the kernel, but am getting the following error:

System.Security.SecurityException

Attempt by method 'Ninject.Web.Mvc.Validation.NinjectDataAnnotationsModelValidatorProvider.GetValidators(System Web.Mvc.ModelMetadata, System.Web.Mvc.ControllerContext, System.Collections.Generic.IEnumerable`1)' to access method 'System.Web.Mvc.DataAnnotationsModelValidator.get_Attribute()' failed.

ASP.NET MVC 2 - Project Areas

The current version of this project still does not work with MVC2's project areas. If two controllers share the same name in different areas of the application (one in the default area, one outside the default area), attempting to access the conflicted-name controller in the default area will produce an ambiguity error.

I corrected this problem in a previous fork of the Ninject MVC project a long time ago, but it has yet to be merged. It is a very easy fix. http://github.com/lakario/ninject.web.mvc

Readme.md contains incomplete information

In the readme, there is a sample example:

public class YourWebApplication : NinjectHttpApplication
{  // […]
  public override IKernel CreateKernel()
  {  // […]
    var kernel = new StandardKernel();
    kernel.AutoLoadModules("~/bin");
    return kernel;
  }
}

But the AutoLoadModules extension method is not defined in this project.

WebViewPage _Layout.cshtml Injections are Null

I am Using Ninject.MVC4 in my ASP.NET MVC4 Project and I am setting Up my Bindings in the created "NinjectWebCommon.cs" file.

I've overwritten the Default View, to Inject an Permissionmanager for my Views

public abstract class MvcBaseWebViewPage<TModel> : WebViewPage<TModel>
{
    [Inject]
    public IPermissionManager PermissionManager { get; set; }
}

and then I've set the new BaseView in the Views web.config

<!--<pages pageBaseType="System.Web.Mvc.WebViewPage">-->
<pages pageBaseType="Gui.Mvc.Views.MvcBaseWebViewPage">

now I've access to the PermissionManager in My Views like

@if (PermissionManager.HasRight(RightsQsMonitor.ConfigurationTrelloVisible))
{
     <li>
      <a href="#" target="_blank">
      <i class="fa fa-trello fa-fw"></i>&nbsp;Trello</a></li>
}

that works great in all Views but for the "_Layout.cshmtl" its not working here is the "PermissionManager" Instance "Null" I think/hope its a bug or do you habe an alternate solution?

How to compile?

I'm new to git and NAnt, and I have no idea how to compile the source. I feel I've tried everything, installed NAnt, git and all I get is errors during the compilation. Tried opening the source in Visual Studio and compiling it that way, but that was also a waste of time.

How do I compile it?

And why not provide the binaries, or at least an proper solution that's possible to open in Visual Studio?

Thanks.

Please state licence type

Hi

Most of the Ninject projects are dual Apache 2.0 / Ms-PL. Please can you add a licence file to this project too?

Thanks
Ian

How may I inject something in the Global.asax ?

I'm starting a web application with MVC3 and Ninject. There is one dependency that I also need in the Global.asax file that needs to be a singleton.

I thought it should be like this:

public class MvcApplication : NinjectHttpApplication
{
IUserAuthentication _auth;

public MvcApplication()
{
    base.AuthenticateRequest += new EventHandler(MvcApplication_AuthenticateRequest);
}

protected override IKernel CreateKernel()
{
    var _kernel = new StandardKernel(new SecurityModule());
    _auth = _kernel.Get<IUserAuthentication>();

    return _kernel;
}

void MvcApplication_AuthenticateRequest(object sender, EventArgs e)
{
    _auth.ToString();
}

But then I saw that _auth is null when MvcApplication_AuthenticateRequest is called.

Then I tried like this:

public class MvcApplication : NinjectHttpApplication
{
ItUserAuthentication _auth;
IKernel _kernel;

public MvcApplication()
{
    _kernel = new StandardKernel(new SecurityModule());
    _auth = _kernel.Get<IUserAuthentication>();
    base.AuthenticateRequest += new EventHandler(MvcApplication_AuthenticateRequest);
}

protected override IKernel CreateKernel()
{
    return _kernel;
}

void MvcApplication_AuthenticateRequest(object sender, EventArgs e)
{
    _auth.ToString();
}

But now I can see that the constructor is being called several times, therefore I will have several IKernel, and I guess that singleton instances won't be so singleton in my app scope.

How should I do it? Using a static variable?

I put this question also in http://stackoverflow.com/questions/5512040/ninject-ing-a-dependency-in-global-asax

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.