Coder Social home page Coder Social logo

ninject.web.common's Introduction

Ninject

Build status codecov NuGet Version NuGet Downloads

Ninject is a lightning-fast, ultra-lightweight dependency injector for .NET applications. It helps you split your application into a collection of loosely-coupled, highly-cohesive pieces, and then glue them back together in a flexible manner. By using Ninject to support your software's architecture, your code will become easier to write, reuse, test, and modify.

Write your code so it's flexible...

public class Samurai {
    public IWeapon Weapon { get; private set; }
    public Samurai(IWeapon weapon) 
    {
        this.Weapon = weapon;
    }
}

...and let Ninject glue it together for you.

public class WarriorModule : NinjectModule
{
    public override void Load() 
    {
        this.Bind<IWeapon>().To<Sword>();
    }
}

Features:

  1. Focused. Too many existing dependency injection projects sacrifice usability for features that aren't often necessary. Each time a feature is added to Ninject, its benefit is weighed against the complexity it adds to everyday use. Our goal is to keep the barrier to entry - the baseline level of knowledge required to use Ninject - as low as possible. Ninject has many advanced features, but understanding them is not required to use the basic features.

  2. Sleek. Framework bloat is a major concern for some projects, and as such, all of Ninject's core functionality is in a single assembly with no dependencies outside the .NET base class library. This single assembly's footprint is approximately 85KB when compiled for release.

  3. Fast. Instead of relying on reflection for invocation, Ninject takes advantage of lightweight code generation in the CLR. This can result in a dramatic (8-50x) improvement in performance in many situations.

  4. Precise. Ninject helps developers get things right the first time around. Rather than relying on XML mapping files and string identifiers to wire up components, Ninject provides a robust domain-specific language. This means that Ninject takes advantage of the capabilities of the language (like type-safety) and the IDE (like IntelliSense and code completion).

  5. Agile. Ninject is designed around a component-based architecture, with customization and evolution in mind. Many facets of the system can be augmented or modified to fit the requirements of each project.

  6. Stealthy. Ninject will not invade your code. You can easily isolate the dependency on Ninject to a single assembly in your project.

  7. Powerful. Ninject includes many advanced features. For example, Ninject is the first dependency injector to support contextual binding, in which a different concrete implementation of a service may be injected depending on the context in which it is requested.

Everything else is in Extensions

Yes, sounds slim and focused, but where is the support for all the features that the competitors have?

Generally, they are maintained as specific focused extensions with owners who keep them in sync and pull in new ideas and fixes fast. These are summarized on the extensions section of the project website. Most are hosted alongside the core project right here.

License

Ninject is intended to be used in both open-source and commercial environments. To allow its use in as many situations as possible, Ninject is dual-licensed. You may choose to use Ninject under either the Apache License, Version 2.0, or the Microsoft Public License (Ms-PL). These licenses are essentially identical, but you are encouraged to evaluate both to determine which best fits your intended use.

Refer to LICENSE.txt for detailed information.

Changes history

Resources

ninject.web.common's People

Contributors

arturdorochowicz avatar brandondahler avatar iappert avatar jonnystoten avatar massteiner avatar noocyte avatar patrickkunz avatar remogloor avatar scott-xu avatar wazaraki 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

Watchers

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

ninject.web.common's Issues

InRequestScope return new istance when used in EndRequest handler in customHttpModule

I try to use InRequestScope in EndRequest for manage transaction UnitOfWork NHIbernate.
but how in this example the request returned is a new istante, not a same "in request".

Imports WebApplication1.Model
Imports Ninject
Imports Ninject.Extensions.Logging

Namespace HttpModule
Public Class CustomHttpModule
Implements IHttpModule

    Private ReadOnly _logger As ILogger
    Private ReadOnly _myClassInRequestScopeFactory As IMyClassInRequestScopeFactory
    Public Sub New(logger As ILogger, myClassInRequestScopeFactory As IMyClassInRequestScopeFactory)
        _logger = logger
        _myClassInRequestScopeFactory = myClassInRequestScopeFactory
    End Sub


    Public Sub Init(context As HttpApplication) Implements IHttpModule.Init
        AddHandler context.BeginRequest, New EventHandler(Sub(s, e) WriteAssertionIstance(s, e, "BeginRequest"))
        AddHandler context.PostLogRequest, New EventHandler(Sub(s, e) WriteAssertionIstance(s, e, "PostLogRequest"))
        AddHandler context.EndRequest, New EventHandler(Sub(s, e) WriteAssertionIstance(s, e, "EndRequest"))
    End Sub


    Private Sub WriteAssertionIstance(sender As Object, e As EventArgs, eventName As String)

        _logger.Info("----> {1} {0}", RequestPhysicalPath(sender), eventName)

        Dim I1 = _myClassInRequestScopeFactory.Create()
        Dim I2 = _myClassInRequestScopeFactory.Create()
        _logger.Info(String.Format("Istance created {0} - {1}", I1.GetHashCode(), I2.GetHashCode()))
    End Sub

    Public Sub Dispose() Implements IHttpModule.Dispose

    End Sub

    Private Shared Function RequestPhysicalPath(source As Object) As String
        Return RequestPhysicalPath(TryCast(source, HttpApplication))
    End Function
    Private Shared Function RequestPhysicalPath(application As HttpApplication) As String
        If application Is Nothing Then Return String.Empty

        Dim context As HttpContext = application.Context
        If context Is Nothing Then Return String.Empty
        Return context.Request.PhysicalPath
    End Function
End Class

End Namespace

this log:

2017-05-24 11:11:40,457 [10] INFO - ----> BeginRequest C:\Lavori\Sviluppo\HttpModuleNinject\WebApplication1\api\redirect
2017-05-24 11:11:40,458 [10] INFO - new MyClassInRequestScope:52697953
2017-05-24 11:11:40,458 [10] INFO - Istance created 52697953 - 52697953
2017-05-24 11:11:40,578 [10] INFO - controller: /api/redirect
2017-05-24 11:11:40,579 [10] INFO - response Redirect:---> /LandingPage.aspx
2017-05-24 11:11:40,594 [10] INFO - ----> PostLogRequest C:\Lavori\Sviluppo\HttpModuleNinject\WebApplication1\api\redirect
2017-05-24 11:11:40,594 [10] INFO - Istance created 52697953 - 52697953
2017-05-24 11:11:40,594 [10] INFO - ----> EndRequest C:\Lavori\Sviluppo\HttpModuleNinject\WebApplication1\api\redirect
2017-05-24 11:11:40,594 [10] INFO - new MyClassInRequestScope:42815147
2017-05-24 11:11:40,594 [10] INFO - Istance created 42815147 - 42815147
2017-05-24 11:11:40,606 [10] INFO - ----> BeginRequest C:\Lavori\Sviluppo\HttpModuleNinject\WebApplication1\LandingPage.aspx
2017-05-24 11:11:40,606 [10] INFO - new MyClassInRequestScope:63130991
2017-05-24 11:11:40,606 [10] INFO - Istance created 63130991 - 63130991
2017-05-24 11:11:40,616 [10] INFO - ----> PostLogRequest C:\Lavori\Sviluppo\HttpModuleNinject\WebApplication1\LandingPage.aspx
2017-05-24 11:11:40,616 [10] INFO - Istance created 63130991 - 63130991
2017-05-24 11:11:40,616 [10] INFO - ----> EndRequest C:\Lavori\Sviluppo\HttpModuleNinject\WebApplication1\LandingPage.aspx
2017-05-24 11:11:40,616 [10] INFO - new MyClassInRequestScope:28805302
2017-05-24 11:11:40,617 [10] INFO - Istance created 28805302 - 28805302

Remove dependency on WebActivator

WebActivator is a nice addition to Microsoft.Web.Infrastructure but it's unsigned assembly. Ninject and Ninject.Web.Common are both signed.
Consider my scenario: I have a project with should be signed, I add Ninject's nuget packages, Ninject.Web.Common also installed WebActivator for me as its dependency. Then I try to build my singed distributive and get an error:
CSC : error CS1577: Assembly generation failed -- Referenced assembly 'WebActivator' does not have a strong name

Anyway WebActivator is only used in generated by nuget package code in App_Start. It would be nice to remove this too as it makes using of Ninject.Web.Common as a dependency for other packages hard.

Problems when Upgrading from 3.2.1 to 3.2.2 - ICache Error

Hi,

I have a Project, where I am using the following Ninject Components:
with this Confoguration everything works fine

<package id="Ninject" version="3.2.2.0" targetFramework="net40" />
<package id="Ninject.MVC4" version="3.2.1.0" targetFramework="net40" />
<package id="Ninject.Web.Common" version="3.2.1.0" targetFramework="net40" />
<package id="Ninject.Web.Common.WebHost" version="3.2.1.0" targetFramework="net40" />

When I update the Ninject.Web.Common to:

<package id="Ninject.Web.Common" version="3.2.2.0" targetFramework="net40" />

I get the following Error, when I am calling the Website:

Error loading Ninject component ICache
No such component has been registered in the kernel's component container.

Suggestions:

  1. If you have created a custom subclass for KernelBase, ensure that you have properly
    implemented the AddComponents() method.
  2. Ensure that you have not removed the component from the container via a call to RemoveAll().
  3. Ensure you have not accidentally created more than one kernel.
    Beschreibung: Unbehandelte Ausnahme beim Ausführen der aktuellen Webanforderung. Überprüfen Sie die Stapelüberwachung, um weitere Informationen über diesen Fehler anzuzeigen und festzustellen, wo der Fehler im Code verursacht wurde.

Ausnahmedetails: System.InvalidOperationException: Error loading Ninject component ICache
No such component has been registered in the kernel's component container.

Suggestions:

  1. If you have created a custom subclass for KernelBase, ensure that you have properly
    implemented the AddComponents() method.
  2. Ensure that you have not removed the component from the container via a call to RemoveAll().
  3. Ensure you have not accidentally created more than one kernel.

Quellfehler:

Beim Ausführen der aktuellen Webanforderung wurde einen unbehandelte Ausnahme generiert. Informationen über den Ursprung und die Position der Ausnahme können mit der Ausnahmestapelüberwachung angezeigt werden.

Stapelüberwachung:

[InvalidOperationException: Error loading Ninject component ICache
No such component has been registered in the kernel's component container.

Suggestions:

  1. If you have created a custom subclass for KernelBase, ensure that you have properly
    implemented the AddComponents() method.
  2. Ensure that you have not removed the component from the container via a call to RemoveAll().
  3. Ensure you have not accidentally created more than one kernel.
    ]
    Ninject.Components.ComponentContainer.Get(Type component) +425
    Ninject.Components.ComponentContainer.Get() +50
    Ninject.Web.Common.<>c__DisplayClass2.b__1(IKernel kernel) +58
    Ninject.GlobalKernelRegistration.MapKernels(Action`1 action) +172
    System.Web.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +80
    System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +165

My NinjectWebCommon.cs looks like:

      /// <summary>
      /// Load your modules or register your services here!
      /// </summary>
      /// <param name="kernel">The kernel.</param>
      private static void RegisterServices(IKernel kernel)
       {
       //Mvc Skeleton Bindings laden
        kernel.Load(new Internal.MvcSkeleton.Gui.Mvc.NinjectBindings());

        //Home Controller Bindings
        kernel.Bind<IRechnungsmonitorDashboardViewModelBuilder>().To<RechnungsmonitorDashboardViewModelBuilder>().InRequestScope();
        kernel.Bind<IOverviewModelBuilder>().To<OverviewModelBuilder>().InRequestScope();
        kernel.Bind<ISearchModelBuilder>().To<SearchModelBuilder>().InRequestScope();
        kernel.Bind<IMantisDashboardViewModelBuilder>().To<MantisDashboardViewModelBuilder>().InRequestScope();
       ....

If you need more Informations please tell me

thx
squadwuschel

Make a dependency to the new WebActivator NuGet package for strong naming support

Ninject.Web.Common has a dependency to WebActivator. The problem with WebActivator is that it isn't stongly named. The creator of WebActivator has build a version 2.x which support stong naming. He only did this in a new NuGet package. See for the new version of WebActivator the following NuGet package: https://www.nuget.org/packages/WebActivatorEx/

For the support thread for WebActivator and stong naming: https://bitbucket.org/davidebbo/webactivator/issue/4/assemblies-are-not-signed

Please update the NuGet package so strong naming is supported by Ninject out of the box.

Thanks!

Release 3.2.4

It looks like the last unstable release was exactly 2 months ago. Are there any blockers to making this a stable release?

Update from 3.3.0 to 3.3.1 causes build server error

I am using net462 and web application.

When packaging a web application using PackageReference and msbuild - it attemps to copy files to a temp location for deploy and it thinks it should copy the App_Start/Ninject.Web.Common.cs but it also thinks it should delete it. So it deletes it from the nuget folder, then later it tries to copy it to the deploy folder based on the file list it generated earlier.

This is all defined in Microsoft.Web.Publishing.targets

<!--Force Copy Of all file to the $(WPPAllFilesInSingleFolder) if needed-->
<CopyPipelineFiles PipelineItems="@(FilesForPackagingFromProject)"
                       SourceDirectory="$(WebPublishPipelineProjectDirectory)"
                       TargetDirectory="$(WPPAllFilesInSingleFolder)"
                       SkipMetadataExcludeTrueItems="True"
                       UpdateItemSpec="True"
                       DeleteItemsMarkAsExcludeTrue ="True"
                   Condition="'@(FilesForPackagingFromProject)' != ''">
  <Output TaskParameter="ResultPipelineItems" ItemName="_FilesForPackagingFromProjectTempory"/>
</CopyPipelineFiles>

Perhaps the bug is in the targets - but I had to roll back to 3.3.0 as I havent figured out a workaround

Any issue with including in referenced assemblies as well as startup web project?

I'm currently using this (along with Ninject.Web.Mvc) in my project, however I have a "Services" project which is used to provided service implementations but is a standard "Code" project (i.e. not an "MVC" project).

Is there any issue with my MVC project referencing other project assemblies that also contain Ninject.Web.Common? I realize there is bootstrapping and other boilerplate code that I want to make sure is not firing off multiple unnecessarily.

Thanks Remo!

NuGet Package Can't Be Installed in .Net 3.5 Solutions

Ninject.Web.Common has WebActivator as a dependency, which has a dependency on Microsoft.Web.Infrastructure. However, Microsoft.Web.Infrastructure doesn't contain a .Net 3.5 assembly and so the dependency installation fails with the following:

Install-Package Ninject.Web.Common
Attempting to resolve dependency 'Ninject (= 3.0.0.0 && < 3.1.0.0)'.
Attempting to resolve dependency 'WebActivator (= 1.5)'.
Attempting to resolve dependency 'Microsoft.Web.Infrastructure (= 1.0.0.0)'.
Successfully installed 'Microsoft.Web.Infrastructure 1.0.0.0'.
Successfully installed 'WebActivator 1.5.1'.
You are downloading Ninject.Web.Common from Ninject Project Contributors, the license agreement to which is available at https://github.com/ninject/ninject.extensions.wcf/raw/master/LICENSE.txt. Check the package for additional dependencies, which may come with their own license agreement(s). Your use of the package and dependencies constitutes your acceptance of their license agreements. If you do not accept the license agreement(s), then delete the relevant components from your device.
Successfully installed 'Ninject.Web.Common 3.0.0.7'.
Successfully added 'Ninject 3.0.1.10' to OSA-CBMClasses.
Successfully uninstalled 'Microsoft.Web.Infrastructure 1.0.0.0'.
Install failed. Rolling back...
Install-Package : Could not install package 'Microsoft.Web.Infrastructure 1.0.0.0'. You are trying to install this package into a project that targets '.NETFram
ework,Version=v3.5', but the package does not contain any assembly references or content files that are compatible with that framework. For more information, co
ntact the package author.
At line:1 char:16
+ Install-Package <<<<  Ninject.Web.Common
    + CategoryInfo          : NotSpecified: (:) [Install-Package], InvalidOperationException
    + FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand

This has a knock-on effect preventing a number of other extensions, such as Ninject.Extensions.Wcf, from installing as they rely on Ninject.Web.Common.

NinjectWebCommon not created after installing Ninject.Web.Common.WebHost package

In the "NuGet Package" section of the wiki article "Setting up an IIS hosted web application" it's suggested that after you install the WebHost package via Install-Package Ninject.Web.Common.WebHost then the NinjectWebCommon class is added to your project's App_Start directory.

However I have observed that this is not the case. I can reproduce this reliably by creating a blank WebApi application in Visual Studio 2017 (Version 15.3.2, using .NET Framework 4.7.1), then installing Ninject.Web.Common.WebHost either via the NuGet UI or Package Manager Console.

Is this a known issue? Would just creating the file manually accomplish the same deal, or is there some other setup related to this class involved>

Update: this was when I didn't specify any version, so version 3.3.0 was installed. When I specify 3.2.0 then the file is created.

Ninject self host WebAPI?

In the documentation that wasn't an mention on how to create self hosted Web API with Ninject? WHat name space should I look under? Thank you.

NinjectWebCommon.cs not added to project

I am developing an MVC 5 application targeting .NET Framework 4.6.1 using Visual Studio 2017. Installing version 3.3.0 of the Ninject.Web.Common package results in the NinjectWebCommon.cs file not being added to the project (the file is not present in the App_Start folder either). Downgrading the package to 3.2.3 solves the issue.

NinjectHttpApplication::Application_End implementation question

I have a question. At the moment Application_End implementation method for NinjectHttpApplication.cs looks like:

    public void Application_End()
    {
        this.bootstrapper.ShutDown();
        this.OnApplicationStopped();
    }

My question is isn't it better to flip the lines to:

    public void Application_End()
    {
        this.OnApplicationStopped();
        this.bootstrapper.ShutDown();
    }

Here are my reasons:

  1. It is more consistent with Application_Start:

    public void Application_Start()
    {
        lock (this)
        {
            this.bootstrapper.Initialize(this.CreateKernel);
            this.onePerRequestHttpModule.ReleaseScopeAtRequestEnd = this.bootstrapper.Kernel.Settings.Get("ReleaseScopeAtRequestEnd", true);
            this.OnApplicationStarted();
        }
    }
    

    Here first the bootstrapper is initialized and then OnApplicationStarted is called. So it makes sense to call OnApplicationStopped first and then shutdown the boostrapper.
    Basically I am trying to say that if the ninject bootstrapper is the first thing that is supposed to be initialized when the application starts, it should be last thing to shutdown when the application ends.

  2. Implementer of NinjectHttpApplication (like MvcApplication) can do more on application shutdown. For instance if I need to do something on Application Shutdown that requires ninject dependency resolution, then it only works if bootstrapper is shutdown after OnApplicationStopped, otherwise it would fail because the kernel is already dead.

RIght now since bootstrapper is shutdown before OnApplicationStopped, basically you cannot do anything that needs ninject resolution.

What do you think?

WebActivator problems - still referenced, and not strongly named

I have a Visual Studio 2012, MVC 4, .NET 4.5 project.

I need OnRequestScope, so today (Feb 4th 2013) I added the latest Ninject.Web.Common nuget package, and added two lines to Global.asax.cs:-

using Ninject.Web.Common;

_ninKernel.Bind<IMyInterface>().To<MyClass>().InRequestScope();

Problem - compilation fails because WebActivator is not strongly named.

I remove the reference to WebActivator.dll from my project (which another issue on here says that I can do). Problem - compilation fails because Ninject.Web.Common is referencing it !

So for all good assemblies that are strongly named (as they should be), Ninject.Web.Common is unusable. Do you really need the reference to WebActivator?

InRequestScope does not really dispose any IDisposables

Steps

  • Create (any) new web application
  • Include current (3.2.x) NuGet packages for Ninject (i.e. Ninject, Ninject.Web.Common, Ninject.MVC3)
  • Create anything that implements IDisposable
  • Add binding and extend to InRequestScope()
  • Observe that Dispose() is never called on HttpApplication.EndRequest

Reason

The corresponding kernel is never registered with OnePerRequestHttpModule because WebCommonNinjectModule fails to call the base implementation in its Load method. This leads to an empty registration being returned in GlobalKernelRegistration.MapKernels when OnePerRequestHttpModule tries to deactivate instances in the HttpApplication.EndRequest event handler, thus no instances are deactivated (and disposed) at all.

Possible workaround until fix

  • Create another (completely empty) module that derives from GlobalKernelRegistrationModule<OnePerRequestHttpModule>
  • Load that module into the desired kernel when you register your bindings
  • This will register the kernel with the module type and properly dispose of request-scoped instances on request end events.

InRequestScope does not work in WCF Service Application

//does not work
Bind<IUnitOfWork>().To<UnitOfWork>().InRequestScope();

//works fine
Bind<IUnitOfWork>().To<UnitOfWork>().InScope(context => HttpContext.Current);

Version:
Ninject 3.2.2.0
Ninject.Extensions.Wcf 3.2.1.0
Ninject.Web.Common 3.2.2.0

Custom middleware will not initialize

Hey everyone - can't seem to find a single thing on the web about this.
Everything setup correctly, controllers accept injection with no problem.
I have a middleware component with an additional constructor argument and when I add the app.builder.use to initialize it, I get an error about it only wanting a constructor with one argument. I tried property injection too with no joy. Basically, what is the exact procedure for ensuring middleware can accept injections?

Here's the Startup code - very simple. "container" is properly built and has everything registered into it.

        appBuilder.UseNinjectMiddleware(() => container);
        appBuilder.Use<LoggerMiddleware>(); // my custom middleware
        appBuilder.UseNinjectWebApi(config);

Anyone have any ideas?

Support for NetCoreApp2.0

Are there any plans in the road map to support netcoreapp2.0 (specifically IApplicationBuilder/IServiceCollection)? I wrote some custom code that basically loads IServiceCollection into an IKernelConfiguration but run into the limitation that ninject can't resolve dependencies of type IEnumerable<T>.

RC2, issue with HttpApplicationInitializationHttpModule Injection

If my webservice global inherits from NinjectHttpApplication, then the application fails with the following error:

Error activating IntPtr
No matching bindings are available, and the type is not self-bindable.
Activation path:
3) Injection of dependency IntPtr into parameter method of constructor of type Func{IKernel}
2) Injection of dependency Func{IKernel} into parameter lazyKernel of constructor of type HttpApplicationInitializationHttpModule

  1. Request for IHttpModule

The following code resolved this error:

public class Global : NinjectHttpApplication
{
    protected override void OnApplicationStarted()
    {
        base.OnApplicationStarted();
    }

    protected override IKernel CreateKernel()
    {
        //define modules loaded by default
        var modules = new INinjectModule[]
        {
            new ServiceModule(),
            new EntityContextModule(),
        };

        IKernel kernel = new StandardKernel(modules);

        //hack for Ninject.Web.Common.HttpApplicationInitializationHttpModule
        kernel.Bind<Func<IKernel>>().ToMethod(c => () => GetKernelInstance());

        return kernel;
    }

    private IKernel GetKernelInstance()
    {
        //this method is deprecated
        return this.Kernel;
    }
}

Is this intended?

WebForms InRequestScope not working

Hi,
I've raised this on Stack Overflow a couple of weeks ago but its not really drawing attention of anyone who knows what this issue is occurring. However, I do believe that InRequestScope isn't working for pages that implement IHttpHandler, [Inject] attributed properties or service locator injections.

The attached sample demonstrates a clean single page classic ASP.NET web application which uses Ninject.Web.Common.WebHost to bind a number of services using InRequestScope (see App_Start\NinjectWebCommon.cs) .

When the test page (TestPage.aspx) is requested and the root service (IServiceA) is requested, the downstream services are instantiated multiple times (see output log).

The same issue occurs for the test handler (TestHandler.ashx).

Furthermore, the [Inject] attribute on the property is not being set in the test page (TestPage.aspx).

NOTE: RegisterServices() is as follows:

	private static void RegisterServices(IKernel kernel)
	{
		kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
		kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();

		kernel.Bind<IServiceA>().To<Services>().InRequestScope();
		kernel.Bind<IServiceB>().To<ServiceB>().InRequestScope();
		kernel.Bind<IServiceC>().To<ServiceC>().InRequestScope();
		kernel.Bind<IServiceD>().To<ServiceD>().InRequestScope();
		kernel.Bind<IServiceE>().To<ServiceE>().InRequestScope();
		kernel.Bind<IServiceF>().To<ServiceF>().InRequestScope();
	}

Requests for IServiceA reports this in the output log:

Constructing Service F
Constructing Service D
Constructing Service F
Constructing Service E
Constructing Service B
Constructing Service F
Constructing Service D
Constructing Service F
Constructing Service E
Constructing Service C
Constructing Service A

Expected output:

Constructing Service F
Constructing Service D
Constructing Service E
Constructing Service B
Constructing Service C
Constructing Service A

TestInRequestScopeWeb.zip

App_Start code not created

Using Visual Studio 2017 I installed Ninject.Web.Common.WebHost via NuGet. It updated the pakcages.config but it did not create Any code in the App_Start directory for the kernel.

No support for HttpApplicationInitializationHttpModule in latest release

We are using Ninject.Web.Common in our project and after updating to the latest version 3.3.0 , there are complilation issues as HttpApplicationInitializationHttpModule is no longer available in the namespace.
What is the alternative to binding IHttpModule to HttpApplicationInitializationHttpModule ?

Ninject kernel in Owin and Webapi in IIS hosted application

I am cross posting this from my StackOverflow question. Any guidance would be appreciated-

I am having a bear of a time getting Ninject to work with the standard ASP.net Identity solution. The stack I am using is WebApi 2.2 and Ninject 3.2.

I am using the Generated NinjectWebCommon.cs file with a slight modification, I made the CreateKernel method public, so I could register it in the OWIN pipeline.

 private static readonly Bootstrapper Bootstrapper = new Bootstrapper();
    private static IKernel _kernel;

    /// <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>
    public static IKernel CreateKernel()
    {
        if (_kernel != null) return _kernel;

        _kernel = new StandardKernel();
        try
        {
            _kernel.Bind<Func<IKernel>>().ToMethod(ctx => () => new Bootstrapper().Kernel);
            _kernel.Bind<IHttpModule>().To<HttpApplicationInitializationHttpModule>();
            RegisterServices(_kernel);
            return _kernel;
        }
        catch
        {
            _kernel.Dispose();
            throw;
        }

    }

In my Startup.Auth.cs file, where OWIN gets configured for ASP.net Identity, I am trying to use the following setup-

 public partial class Startup
{
    static Startup()
    {
        PublicClientId = "self";
        OAuthOptions = new OAuthAuthorizationServerOptions
        {
            TokenEndpointPath = new PathString("/Token"),
            Provider = new ApplicationOAuthProvider(PublicClientId),
            RefreshTokenProvider = new RefreshTokenProvider(),
            AuthorizeEndpointPath = new PathString("/api/Account/ExternalLogin"),
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(20),
#if DEBUG
            AllowInsecureHttp = true
#endif
        };
    }

    public static OAuthAuthorizationServerOptions OAuthOptions { get; private set; }

    public static string PublicClientId { get; private set; }

    // For more information on configuring authentication, please visit http://go.microsoft.com/fwlink/?LinkId=301864
    public void ConfigureAuth(IAppBuilder app)
    {
        //allow cors
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
        //use ninject in owin
        app.UseNinjectMiddleware(NinjectWebCommon.CreateKernel);
        app.UseWebApi(GlobalConfiguration.Configuration);


        // Enable the application to use bearer tokens to authenticate users
        var opts = new OAuthBearerAuthenticationOptions
        {
            AuthenticationType = "Bearer",
            AuthenticationMode = Microsoft.Owin.Security.AuthenticationMode.Active,
            Provider = new QueryStringOAuthBearerProvider("access_token")
        };
        app.UseOAuthBearerAuthentication(opts);
        app.UseOAuthAuthorizationServer(OAuthOptions);
    }
}

The problem I am getting is whenever use the app.UseNinjectMiddleware(NinjectWebCommon.CreateKernel); the app throws a "Sequence contains no elements error" with the following stacktrace-

[InvalidOperationException: Sequence contains no elements]
   System.Linq.Enumerable.Single(IEnumerable`1 source) +315
   Ninject.Web.Mvc.NinjectMvcHttpApplicationPlugin.Start() +87
   Ninject.Web.Common.Bootstrapper.<Initialize>b__0(INinjectHttpApplicationPlugin c) +29
   Ninject.Infrastructure.Language.ExtensionsForIEnumerableOfT.Map(IEnumerable`1 series, Action`1 action) +194
   Ninject.Web.Common.Bootstrapper.Initialize(Func`1 createKernelCallback) +205
   Ninject.Web.Common.OwinHost.<Execute>d__1.MoveNext() +257
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
   System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
   Microsoft.Owin.Cors.<Invoke>d__0.MoveNext() +1205
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
   System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.<RunApp>d__5.MoveNext() +287
   System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) +93
   System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) +52
   System.Runtime.CompilerServices.TaskAwaiter.GetResult() +21
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.<DoFinalWork>d__2.MoveNext() +272
   System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() +22
   Microsoft.Owin.Host.SystemWeb.Infrastructure.ErrorState.Rethrow() +33
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.StageAsyncResult.End(IAsyncResult ar) +150
   Microsoft.Owin.Host.SystemWeb.IntegratedPipeline.IntegratedPipelineContext.EndFinalWork(IAsyncResult ar) +42
   System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +415
   System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155

Am I doing something wrong in my setup of the ninject kernel to be used in OWIN and in the rest of my IIS hosted web application?

Nuget Package does not work with Owin 3.0

Install-Package : Updating 'Microsoft.Owin 3.0.0' to 'Microsoft.Owin 2.0.0' failed. Unable to find versions of 'Microsoft.AspNet.SignalR.Core, Microsoft.Owin.Security, Microsoft.Owin.StaticFiles' that
are compatible with 'Microsoft.Owin 2.0.0'.
At line:1 char:1

  • Install-Package Ninject.Web.Common.OwinHost -ProjectName CommonWeb
  • - CategoryInfo          : NotSpecified: (:) [Install-Package], InvalidOperationException
    - FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.InstallPackageCommand
    

OWIN + Ninject w/ UseNinjectMiddleware doesn't dispose

When registering a Ninject kernel as a middleware component in OWIN using UseNinjectMiddleware any injected object that implements IDisposable does not get disposed of at the end of a request.

I've put in console prints to watch when an instance was created and disposed of. I've noticed that instances are being created with each request but not being disposed of until some random time later.

I created an empty project to find the root cause. I used a simple model that tracks its instance number so I can tell what is being created and disposed of.

Model:

public class Demo : IDemo, IDisposable {
    public static int InstanceCount = 1; //Tracks the current number of 
                                         //instances that have been created.
    public Demo() {
        Id = InstanceCount++; 
        Debug.WriteLine("Initialized Instance " + Id);
    }
    public int Id { get; set; }
    public void Dispose() {
        Debug.WriteLine("Disposed instance" + Id);
        Id = -1;
    }
}

public interface IDemo {
    int Id { get; set; }
}

Controller

public class HomeController : Controller {
    private readonly IDemo demo;
    public HomeController(IDemo demo) { this.demo = demo; }

    public ActionResult Index() {
        ViewBag.Id = demo.Id;
        return View();
    }
}

Startup file:

public class Startup {
    public void Configuration(IAppBuilder app) {
        var kernel = CreateKernel();
        app.UseNinjectMiddleware(() => kernel);
    }

    public IKernel CreateKernel() {
        var kernel = new StandardKernel();
        kernel.Bind<IDemo>().To<Demo>().InRequestScope();
        return kernel;
    }
}

I've also made sure all of the packages are up to date since this was a known issue in a previous version of Ninject.

<?xml version="1.0" encoding="utf-8"?>
<packages>
  <package id="Microsoft.AspNet.Mvc" version="5.2.7" targetFramework="net462" />
  <package id="Microsoft.AspNet.Razor" version="3.2.7" targetFramework="net462" />
  <package id="Microsoft.AspNet.WebPages" version="3.2.7" targetFramework="net462" />
  <package id="Microsoft.CodeDom.Providers.DotNetCompilerPlatform" version="2.0.1" targetFramework="net462" />
  <package id="Microsoft.Owin" version="4.0.1" targetFramework="net462" />
  <package id="Microsoft.Owin.Host.SystemWeb" version="4.0.1" targetFramework="net462" />
  <package id="Microsoft.Web.Infrastructure" version="1.0.0.0" targetFramework="net462" />
  <package id="Ninject" version="3.3.4" targetFramework="net462" />
  <package id="Ninject.MVC5" version="3.3.0" targetFramework="net462" />
  <package id="Ninject.Web.Common" version="3.3.1" targetFramework="net462" />
  <package id="Ninject.Web.Common.OwinHost" version="3.3.1" targetFramework="net462" />
  <package id="Ninject.Web.Common.WebHost" version="3.3.1" targetFramework="net462" />
  <package id="Owin" version="1.0" targetFramework="net462" />
  <package id="WebActivatorEx" version="2.2.0" targetFramework="net462" />
</packages>

Expected

When viewing the home page for the application each request should print out:

Initialized Instance #

and then at the end of the request

Disposed instance #

where # is the current instance number

Actual

Each time the page is viewed only the initialization is printed.

Initialized Instance #

Question

Am I doing something wrong or is this a bug with Ninject and Owin? Is there a way to fix this issue?

RC2 Does not work

Hi Reemo
I'm just opening a ticket here so that we can skip Stackoverflow

http://stackoverflow.com/questions/8712682/ninject-mvc-together-with-wcf-extension-does-not-work-with-inrequestscope

I get two different errors on two different machines, both using fresh isolated MVC3 projects.

"Could not load type 'System.Runtime.CompilerServices.ExtensionAttribute' from assembly 'mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'."

and

"Method not found: 'System.Delegate System.Reflection.MethodInfo.CreateDelegate(System.Type)'."

Tried both with Webactivator 1.4.4 and 1.5

Problem with Ninject.Web.Common.Xml NuGet Package

Just installed Ninject.Web.Common.Xml and found the packages\Ninject.Web.Common.Xml directory has no lib folder so contains no binaries. Because of this the reference is not added to project and the assembly can't be used.

I cloned the repo and built it locally to get round the issue, but would be nice to have the NuGet package working!

Thanks

HttpRequestMessage GetDependencyScope in a DelegatingHandler

My WebAPI Startup class looks like this:

var config = new HttpConfiguration();
WebApiConfig.Register(config);
app.UseHttpMessageHandler(HttpClientFactory.CreatePipeline(
    new AuthorizationDelegatingHandler(),
    new DelegatingHandler[]
    {
        new LoggingDelegatingHandler(),
        new LanguageMessageHandler(),
        new ValidateAccountPaymentStatusHandler()
    }));
app.UseNinjectMiddleware(CreateKernel).UseNinjectWebApi(config);

In my LoggingDelegatingHandler I have the following call:

var logger = request.GetDependencyScope().GetService<ILogger>();

However, request.GetDependencyScope() is always null.

Any idea why?

Can I suppress disposing when using InRequestScope?

I have a service which is supposed to accumulate data within its lifetime and then flush these data to an external resource upon the end of an HTTP request.
Its lifetime should be restricted to one http request and that's why I use InRequestScope. But seems like it cannot give 100% guarantee that my service gets Disposeed upon the request end. Moreover, this approach would make my code too dependant on Ninject.
That's why I use HttpContext.Current.DisposeOnPipelineCompleted to guarantee what I need and be able to re-use my service in non-Ninject projects.
However, InRequestScope after some time fires Dispose meaning this method gets invoked twice for the same object which is not good.
I may introduce some locks and flags to avoid double execution but this is going to make my code dirty. Thus, my question: is there a way to ask Ninject not to Dispose some services?

InRequestScope object created twice in async/await controller

See the following example:

    public async Task<ActionResult> Index()
    {
            var p1 = Resolve<IRequestScopedObject>();

            await SomethingAsync();

            var p2 = Resolve<IRequestScopedObject>();

            Trace.WriteLine(p2 == p1); // This is always false

            return View();
    }

As IRequestScopedObject is registered InRequestScope() and the EndRequest event doesn't get fired until the Index() method finishes, I would expect that p1 and p2 should be the same object.

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.