Coder Social home page Coder Social logo

ninject'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's People

Contributors

aaubry avatar apdmatos avatar bartelink avatar boblangley avatar brunojuchli avatar casualjim avatar danielmarbach avatar davethieben avatar dholtdev avatar drieseng avatar giorgi avatar iappert avatar idavis avatar idisposable avatar jamesmanning avatar jarrettmeyer avatar kaylanimis avatar litee avatar lord-executor avatar markashleybell avatar petejohanson avatar philippdolder avatar remogloor avatar rolandka avatar scott-xu avatar scottcarr avatar sglienke avatar ungood 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  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

ninject's Issues

Named Bindings are considered have the same priority as nameless bindings

The following test probably should not fail:
[Fact]
public ShouldResolveWithDefaultBinding()
{
var kernel = new StandardKernel();
kernel.Bind().To()
.WithPropertyValue("Name","Shishi-Oh");
kernel.Bind().To()
.WithPropertyValue("Name", "Masamune")
.Named("Masamune");
var weapon = kernel.Get();
weapon.ShouldBeInstanceOf();
weapon.Name.ShouldBe("Shishi-Oh");
}

Circular dependency results in stack overflow when interfaces are used.

The following test case causes a stack overflow in the task runner:

public class WhenDependenciesHaveTwoWayIndirectCircularReferenceBetweenConstructors : CircularDependenciesContext
{
    internal interface ITwoWayConstructorBar { }

    internal interface ITwoWayConstructorFoo { }

    internal class TwoWayConstructorFoo : ITwoWayConstructorFoo
    {
        public TwoWayConstructorFoo(ITwoWayConstructorBar bar) { }
    }

    internal class TwoWayConstructorBar : ITwoWayConstructorBar
    {
        public TwoWayConstructorBar(StandardKernel kernel)
        {
            kernel.Get<ITwoWayConstructorFoo>();
        }
    }

    public WhenDependenciesHaveTwoWayIndirectCircularReferenceBetweenConstructors()
    {
        kernel.Bind<ITwoWayConstructorFoo>().To<TwoWayConstructorFoo>().InSingletonScope();
        kernel.Bind<ITwoWayConstructorBar>().To<TwoWayConstructorBar>().InSingletonScope();
        kernel.Bind<StandardKernel>().ToConstant(kernel);
    }

    [Fact]
    public void DoesNotThrowExceptionIfHookIsCreated()
    {
        var request = new Request(typeof(ITwoWayConstructorFoo), null, Enumerable.Empty<IParameter>(), null, false, false);
        Assert.DoesNotThrow(() => kernel.Resolve(request));
    }

    [Fact]
    public void ThrowsActivationExceptionWhenHookIsResolved()
    {
        Assert.Throws<ActivationException>(() => kernel.Get<ITwoWayConstructorFoo>());
    }
}

Define order on binding for NinjectModule

On KernelBase there's not the possibility to define the order in which the modules are added.
As an illustration, the following attribute can be used for decorate the module

[ModuleLoadPriority(1)]

The declared priority on the module will then be used to define the order in which modules are added.

MethodAccessException in medium trust for interface properties

When running in medium trust, Ninject will throw a MethodAccessException when it tries to resolve a type whose interface has a property. The exception is thrown in line 185 of ExtensionsForMemberInfo.cs. That method has a branch for #if MEDIUM_TRUST which is never called even in medium trust. Setting it explicitly in the project file <DefineConstants> property seemed to have no effect.

See repro steps and exception details below.

Repro steps

  1. Create a new web project.
    (I used Visual Studio's ASP.NET MVC 4 Web Application, Web API template.)
  2. Install the Ninject NuGet package on the project.
    (I used 3.0.1.10.)
  3. Add the following code to Global.asax:
    public class WebApiApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            // default template code
            // [snip]

            // construct Ninject container
            INinjectSettings settings = new NinjectSettings
            {
                UseReflectionBasedInjection = true,    // disable code generation for partial trust
                InjectNonPublic = false,               // disable private reflection for partial trust
                InjectParentPrivateProperties = false, // reduce magic
                LoadExtensions = false                 // reduce magic
            };
            IKernel kernel = new StandardKernel(new Module());

            // example injection
            IDependency dependency = kernel.Get<IDependency>();
        }
    }

    /// <summary>A dependency to be loaded through Ninject.</summary>
    public interface IDependency
    {
        string ArbitraryValue { get; set; }
    }

    /// <summary>A dependency implementation to be loaded through Ninject.</summary>
    public class Dependency : IDependency
    {
        public string ArbitraryValue { get; set; }
    }

    /// <summary>The Ninject module that binds the example dependency.</summary>
    public class Module : NinjectModule
    {
        /// <summary>Loads the module into the kernel.</summary>
        public override void Load()
        {
            this.Bind<IDependency>().To<Dependency>();
        }
    }
  1. Add the following configuration to web.config:
<trust level="Medium"/>

Exception details

System.MethodAccessException: Attempt by method 'Ninject.Infrastructure.Language.ExtensionsForMemberInfo.GetParentDefinition(System.Reflection.MethodInfo, System.Reflection.BindingFlags)' to access method 'System.Reflection.RuntimeMethodInfo.GetParentDefinition()' failed.

Source File: ExtensionsForMemberInfo.cs    Line: 180 

Stack Trace: 

[MethodAccessException: Attempt by method 'Ninject.Infrastructure.Language.ExtensionsForMemberInfo.GetParentDefinition(System.Reflection.MethodInfo, System.Reflection.BindingFlags)' to access method 'System.Reflection.RuntimeMethodInfo.GetParentDefinition()' failed.]
   System.RuntimeMethodHandle.PerformSecurityCheck(Object obj, RuntimeMethodHandleInternal method, RuntimeType parent, UInt32 invocationFlags) +0
   System.RuntimeMethodHandle.PerformSecurityCheck(Object obj, IRuntimeMethodInfo method, RuntimeType parent, UInt32 invocationFlags) +31
   System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) +156
   Ninject.Infrastructure.Language.ExtensionsForMemberInfo.GetParentDefinition(MethodInfo method, BindingFlags flags) in ExtensionsForMemberInfo.cs:180
   Ninject.Infrastructure.Language.ExtensionsForMemberInfo.GetParentDefinition(PropertyInfo property) in ExtensionsForMemberInfo.cs:151
   Ninject.Infrastructure.Language.ExtensionsForMemberInfo.IsDefined(PropertyInfo element, Type attributeType, Boolean inherit) in ExtensionsForMemberInfo.cs:212
   Ninject.Infrastructure.Language.ExtensionsForMemberInfo.HasAttribute(MemberInfo member, Type type) in ExtensionsForMemberInfo.cs:72
   Ninject.Selection.Heuristics.StandardInjectionHeuristic.ShouldInject(MemberInfo member) in StandardInjectionHeuristic.cs:45
   Ninject.Selection.<>c__DisplayClass3.<SelectPropertiesForInjection>b__2(IInjectionHeuristic h) in Selector.cs:95
   System.Linq.Enumerable.Any(IEnumerable`1 source, Func`2 predicate) +146
   Ninject.Selection.Selector.<SelectPropertiesForInjection>b__1(PropertyInfo p) in Selector.cs:95
   System.Linq.WhereEnumerableIterator`1.MoveNext() +139
   System.Collections.Generic.List`1.InsertRange(Int32 index, IEnumerable`1 collection) +392
   Ninject.Selection.Selector.SelectPropertiesForInjection(Type type) in Selector.cs:92
   Ninject.Planning.Strategies.PropertyReflectionStrategy.Execute(IPlan plan) in PropertyReflectionStrategy.cs:58
   Ninject.Planning.<>c__DisplayClass1.<CreateNewPlan>b__0(IPlanningStrategy s) in Planner.cs:109
   Ninject.Infrastructure.Language.ExtensionsForIEnumerableOfT.Map(IEnumerable`1 series, Action`1 action) in ExtensionsForIEnumerableOfT.cs:32
   Ninject.Planning.Planner.CreateNewPlan(Type type) in Planner.cs:109
   Ninject.Planning.Planner.GetPlan(Type type) in Planner.cs:71
   Ninject.Activation.Providers.StandardProvider.Create(IContext context) in StandardProvider.cs:77
   Ninject.Activation.Context.Resolve() in Context.cs:157
   Ninject.<>c__DisplayClass10.<Resolve>b__c(IBinding binding) in KernelBase.cs:386
   System.Linq.WhereSelectEnumerableIterator`2.MoveNext() +145
   System.Linq.<CastIterator>d__b1`1.MoveNext() +85
   System.Linq.Enumerable.Single(IEnumerable`1 source) +121
   Ninject.ResolutionExtensions.Get(IResolutionRoot root, IParameter[] parameters) in ResolutionExtensions.cs:37
   NinjectPartialTrustRepro2.WebApiApplication.Application_Start() in c:\Users\plamondon\Documents\Visual Studio 11\Projects\NinjectPartialTrustRepro2\NinjectPartialTrustRepro2\Global.asax.cs:35

[HttpException (0x80004005): Attempt by method 'Ninject.Infrastructure.Language.ExtensionsForMemberInfo.GetParentDefinition(System.Reflection.MethodInfo, System.Reflection.BindingFlags)' to access method 'System.Reflection.RuntimeMethodInfo.GetParentDefinition()' failed.]
   System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +9841101
   System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +118
   System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +172
   System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +336
   System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +296

[HttpException (0x80004005): Attempt by method 'Ninject.Infrastructure.Language.ExtensionsForMemberInfo.GetParentDefinition(System.Reflection.MethodInfo, System.Reflection.BindingFlags)' to access method 'System.Reflection.RuntimeMethodInfo.GetParentDefinition()' failed.]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9850940
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +254

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.17626

GetHashCode dependency in ActivationCache

The ActivationCache uses a dictionary/hashtable to cache instances. It uses the ReferenceEqualWeakReference class, which uses the GetHashCode method of the target instance to obtain a hashcode, creating a dependency on GetHashCode before the object may be fully activated.

As an illustration, the following test fails with an exception.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Xunit;

namespace Ninject.Tests.Integration
{
   public class HashCodeSample
   {
      private Boolean initialized;

      [Inject]
      public void Initialize()
      {
         initialized = true;
      }

      public override int GetHashCode()
      {
         if (initialized)
            return 42; // whatever, this could be a value based on data set in Initialize

         // Otherwise throw, or return a random hashcode (say).
         throw new Exception("Not Initialized");
      }
   }

   public class ActivationCacheGetHashCodeTest
   {
      [Fact]
      public void CanCreateHashCodeSample()
      {
         var kernel = new StandardKernel();

         kernel.Bind<HashCodeSample>().ToSelf();

         var sample = kernel.Get<HashCodeSample>();
      }
   }
}

I believe Ninject should not rely on GetHashCode. As ReferenceEqualWeakReference uses reference equality anyway, one could consider using RuntimeHelpers.GetHashCode instead to obtain the hashcode in ReferenceEqualWeakReference?

If this behaviour is by design, however, I'd love to hear it confirmed / clarified.

XML Serialization provider ?

Hello,

I'm working on an application and i would like to use XML serialization for classes that are in the Kernel, so I guess I could write an XML Provided and do something like :

Bind<ISomething>().ToProvider(new XMLProvider("file.xml"));

This causes some problems.

First, imagine I want to save my object back to file.xml, I really don't want to duplicate the code to do this (load from the provider and save from some other logics) because this would be a painful boilerplate. So how could I use the provider to also do the save job ?

To solve this problem, I imagine that the provider could listen on "Saving" events from the instance it creates (using an ISaveable or something like this).

But in my application, I also would like to be able to create new instances of a certain class at any time, how would I re-register it in the Kernel in this case ? Is there any best practice to achieve this ?

StandardKernel constructor throws NotSupportedException with multiple PrivatePaths in AppDomain

We are using multiple paths for ou AppDomain private path, because we want to be able to load plugins dynamically, and their dlls are in dfferent folders. However, when we use AppDomain.CurrentDomain.AppendPrivatePath() more than one time (to add several different folders where plugin binaries are searched), StandardKernel constructor throws exception:

System.NotSupportedException was unhandled
  Message="The given path's format is not supported."
  Source="mscorlib"
  StackTrace:
       at System.Security.Util.StringExpressionSet.CanonicalizePath(String path, Boolean needFullPath)
       at System.Security.Util.StringExpressionSet.CreateListFromExpressions(String[] str, Boolean needFullPath)
       at System.Security.Permissions.FileIOPermission.AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, Boolean checkForDuplicates, Boolean needFullPath, Boolean copyPathList)
       at System.Security.Permissions.FileIOPermission..ctor(FileIOPermissionAccess access, String[] pathList, Boolean checkForDuplicates, Boolean needFullPath)
       at System.IO.Path.GetFullPath(String path)
       at Ninject.Modules.ModuleLoader.NormalizePath(String path)
       at Ninject.Modules.ModuleLoader.GetFilesMatchingPattern(String pattern)
       at Ninject.Modules.ModuleLoader.<LoadModules>b__0(String pattern)
       at System.Linq.Enumerable.<SelectManyIterator>d__14`2.MoveNext()
       at System.Linq.Lookup`2.Create[TSource](IEnumerable`1 source, Func`2 keySelector, Func`2 elementSelector, IEqualityComparer`1 comparer)
       at System.Linq.GroupedEnumerable`3.GetEnumerator()
       at Ninject.Modules.ModuleLoader.LoadModules(IEnumerable`1 patterns)
       at Ninject.KernelBase.Load(IEnumerable`1 filePatterns)
       at Ninject.KernelBase..ctor(IComponentContainer components, INinjectSettings settings, INinjectModule[] modules)
       at Ninject.KernelBase..ctor(INinjectModule[] modules)
       at Ninject.StandardKernel..ctor(INinjectModule[] modules)
       at NinjectMultiplePathBug.Program.Main(String[] args) in D:\Dokumenty\Programming\C#\Ninject\NinjectMultiplePathBug\Program.cs:line 29
       at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()

This is minimal reproduction case:

using System;
using System.IO;
using Ninject;
using Ninject.Modules;

namespace NinjectMultiplePathBug
{
    public class TestModule : NinjectModule
    {
        public override void Load()
        {
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
#pragma warning disable 612,618
            AppDomain.CurrentDomain.AppendPrivatePath(@"C:\");
            AppDomain.CurrentDomain.AppendPrivatePath(@"D:\");
#pragma warning restore 612,618

            var kernel = new StandardKernel(new TestModule());
        }
    }
}

Error originates in NInject/Modules/ModuleLoader on line 90 in NormalizePath(string path) where GetBaseDirectory() returns compound path (like "C:\FirstPath;C:\SecondPath"), and later on Path.GetFullPath(path) crashes on such string.

As the AppendPrivatePath is obsolete (but we have found no other way of loading plugins on the fly from different directories), would you want to fix the bug? The alternative is that we'd do a quick private hack on GetFilesMatchingPattern that would just split the string, and did the rest on separated paths.

NPE binding an instance with a property

I am using the current Mono download and the following test case fails with a null pointer exception.

The same test works with the previous version of Ninject, 2.2.0.0.

    interface ITestInterface
    {
        string Property { get; set; }
    }

    class TestImpl : ITestInterface
    {
        public string Property {
            get { return "Foo";}
            set { }
        }
    }

    [TestFixture()]
    public class ModelModuleTest
    {

        [Test()]
        public void TestInterfaceBinding ()
        {
            IKernel kernel = new StandardKernel ();
            kernel.Bind<ITestInterface> ().To<TestImpl> ();
            Assert.IsNotNull (kernel.Get<ITestInterface> ());
        }
    }

Same error occurs when binding ToConstant (new TestImpl ()).

Unfortunately I don't know how to copy the stack trace from MonoDevelop :(

Ninject identifies modules based on a class name rather than a full anem

Ninject does not allow loading of a module twice (and that's good) but the problem is that it identifies modules just by a class name instead of a full name (with namespace). This is painfull if you have multiple projects in a solution with seperate modules to configure them and you follow a simple naming convention like DefaultModule, MockingModule, etc. for each project. Now you have to bend your convention to something like ProjectADefaultModuel, ProjectBDefaultModule, ProjectCDefaultModuel to make it work.
It would be better if modules were identified by a full name (with full namespace).

NullReferenceException when doing parallel kernel.Get()

I upgraded to the latest version of Ninject (2.1.0.77) using the .NET 4.0 targeted assembly from teamcity. (http://teamcity.codebetter.com/project.html?projectId=project3)

The impetus behind this upgrade was a bug in the release of 2.0 which caused errors when multi-threading. (http://groups.google.com/group/ninject/browse_thread/thread/c812a965514dedde)

The problem is that now I'm a getting different multithread-related error. The following gist shows my code and stack trace: http://gist.github.com/645518

I'm using the MVC, WCF, and Convention extensions as well. Please let me know if you need any clarification.

GetAll will not return all instances in case conditional and unconditional bindings are mixed

The following unit test will not pass. Only one instance is returned.

    [Fact]
    public void ReturnsSeriesOfItemsConditionalsFirst()
    {
        kernel.Bind<IWeapon>().To<Sword>();
        kernel.Bind<IWeapon>().To<Shuriken>().When(ctx => true);

        var weapons = kernel.GetAll<IWeapon>().ToArray();

        weapons.ShouldNotBeNull();
        weapons.Length.ShouldBe(2);
        weapons[0].ShouldBeInstanceOf<Shuriken>();
        weapons[1].ShouldBeInstanceOf<Sword>();
    }

KernelBase.CanResolve returns true even for Bindings with unsatisfied conditions

The title says most of it. If you have a binding with a condition CanResolve can return true even if that condition isn't met by the request. See the following commit for a test and a proposed solution.

http://github.com/Talljoe/ninject/commit/9851b4a21f3dba88f75636e7dfdbd80798824dba

I ran across this problem with OpenRasta and it's AllResolvablePropertiesInjectionHeuristic. It's logic seems reasonable so I patched Ninject.

IContainer instead of IKernel

What about renaming IKernel into IContainer and everything containing Kernel word because Kernel is so confusing in terms of dependency injection. I think container is more suitable name for DI container. Kernel is entry point of the application. I also think this is good time to make this change because you are switching major version from 2 to 3.

Agree?

Problem with generic type subclass injection

In your file
FormatExtentions.cs
line 162: sb.Append(type.Name.Substring(0, type.Name.LastIndexOf('`')));

you are looking for a [grave accent]. (like this: ù, but on a space, I can't insert one because then github thinks I'm opening a code block) in generic type names, assuming it is there. The injection setup will crash if it's not. This is the case when using a type like SomeClass< T >.ISomeInterface, because the "name" property will return "SomeInterface" as value, and then the substring method crashes because it cannot find the `.

So basically, when injecting a subtype of a generic class, it will return true on querying "IsGeneric" and then return a type name without a [grave accent] in it, crashing the binding.

I hope this was put clearly enough. Thanks for providing this excellent tool for free!

PS: I'm using the MVC3 library to go along with this, I hope the MVC4 equivalent will be out soon! :)

Common Service Locator does not resolve an instance without a name.

The following test currently fails with an Activation Exception:

[Fact] 
public ShouldResolveWithoutNameBeingGiven() 
{ 
    var kernel = new StandardKernel(); 
    kernel.Bind<IWeapon>.To<Sword>(); 
    var locator = new NinjectServiceLocator(kernel); 
    var weapon = locator.GetInstance<IWeapon>(); 
    weapon.ShouldNotBeNull(); 
    weapon.ShouldBeInstanceOf<Sword>(); 
} 

The fix is a simple one. Change line 30 of NinjectServiceLocator.cs to:

return key == null ? Kernel.Get(serviceType) : Kernel.Get(serviceType,key);

private property injection windows phone

Private or internal properties cannot be injected using the [Inject] attribute and there is no setting in the wp7 version of the kernel to allow this either.

Also it would benice if properties without {get;set;} could be injectable too.

Exception on resolving instance when type registration has mixed concrete binding and open generics binding

Here is repro code for it

using System;
using Ninject.Modules;

namespace Ninject.Repro {
    class Program {
        static void Main(string[] args) {
            var kernel = new StandardKernel(new Module());

            //works as expected
            var intInjectable = kernel.Get<IInjectable<int>>();
            intInjectable.Inject(123);

            /* throws an exception 
             Unhandled Exception: Ninject.ActivationException: Error activating IInjectable{string}
More than one matching bindings are available.
Activation path:
  1) Request for IInjectable{string}

Suggestions:
  1) Ensure that you have defined a binding for IInjectable{string} only once.

   at Ninject.KernelBase.Resolve(IRequest request)
   at Ninject.ResolutionExtensions.GetResolutionIterator(IResolutionRoot root, Type service, Func`2 constraint, IEnumerable`1 parameters, Boolean isOptional, Boolean isUnique)
   at Ninject.ResolutionExtensions.Get[T](IResolutionRoot root, IParameter[] parameters)
    ...
             */
            var stringInjectable = kernel.Get<IInjectable<string>>();
            stringInjectable.Inject("Value");
        }
    }

    public class Module : NinjectModule {
        public override void Load() {
            this.Bind<IInjectable<string>>().To<StringInjectable>();

            this.Bind(typeof(IInjectable<>)).To(typeof(Injectable<>));
        }
    }


    public interface IInjectable<T> {
        void Inject(T item);
    }
    public class StringInjectable : IInjectable<string> {
        public void Inject(string item) {
            Console.WriteLine("Special case injection");
        }
    }
    public class Injectable<T> : IInjectable<T> {
        public void Inject(T item) {
            Console.WriteLine(typeof(T).FullName);
        }
    }
}

Unable to install by NuGet

  1. Create new project, MVC 3 Web application.
  2. Open package manager control.
  3. Run install-package ninject

Actual result:
PM> install-package ninject
You are downloading Ninject from Ninject Project Contributors, the license agreement to which is available at https://github.com/ninject/ninject/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 2.2.1.0'
Install-Package : Unable to find assembly references that are compatible with the target framework '.NETFramework,Version=v4.0'
At line:1 char:16

  • install-package <<<< ninject
    • CategoryInfo : NotSpecified: (:) [Install-Package], InvalidOperationException
    • FullyQualifiedErrorId : NuGet.VisualStudio.Cmdlets.InstallPackageCmdlet

PM>

Expected result:
Successfully installed.

Later if I try to add reference manually, application could not load ninject.dll

Circular Dependency should only be an exception if no scope defined.

Currently an activation exception is thrown whenever a circular dependency is found. It does not make sense to me, and I think it should be changed, that if a scope is introduced that keeps the dependency from sending the resolver into infinite recursion, then the exception should not be thrown.

In other words, currently the CircularDependenciesTests all bind the test classes as InSingletonScope and expect an exception. It seems like these tests should not expect an exception since the second instance of Foo (needed by Bar) would be the first instance already created. Another set of test cases should not bind as InSingletonScope and should expect an exception.

Is there a reasonable argument against this?

NullReferenceException Caused By Property With Private Setter

Hi,

Try the following .NET 4.0 console application:

using Ninject;

namespace NinjectBug
{
internal class Program
{
public static void Main()
{
var kernel = new StandardKernel();

        kernel.Bind<ISomeInterface>().To<SomeInterfaceImplementation>().InTransientScope();
        kernel.Bind<InjectMe>().ToSelf();

        var injectMe = kernel.TryGet<InjectMe>();
    }
}

public interface ISomeInterface
{
}

public sealed class SomeInterfaceImplementation : ISomeInterface
{
}

public class InjectMe
{
    [Inject]
    public string PublicPrivateProperty
    {
        get;
        private set;
    }
}

}

Running this gives me a NullReferenceException inside Ninject.Injection.DynamicMethodInjectorFactory.EmitMethodCall. Would expect a more useful exception, e.g. ActivationException with the name of the offending property.

Thanks,

Kev

Unknown Error when trying to clone repository

I get the following error when cloning the repository. I get the error both when I clone a read-only copy or when I fork a copy then clone.

"remote: error: object directory ./objects/../../data/repositories/4/nw/4e/8a/19/145356/network.git/objects does not exist; check .git/objects/info/alternates."

No clue what it is.

Ctor Selection with Default Parameters

Ian: "optional parameters and their resolution/scoring"
Remo: Scoring has to be reworked anyway
Ian: any ideas you what you would want to do in a rework?
we have all thought about it. default ctor, no satisfiable ctors, ctors with default params that can't be otherwise satisfied, ctors with default params that can be fully or partially satisfied
what happens if you have two ctors of equal params. but one uses default and one can be injected, which do we prefer, or do we error and make them disambiguate? -and supplied parameters.
Joe: And ctors that can be satisifed with implicit/missing bindings.
Ian: from this thread: http://groups.google.com/group/ninject/browse_thread/thread/e725483345594bed/db3a2d18a407f0b2?lnk=gst&q=Let.Inject#db3a2d18a407f0b2
any thoughts joe?
Joe: reading...
Remo: I think default parameters have no influence
At least no other than self bindable types
Ian: given that they are compile time constants that are not self bindable
Remo: Can you have default params that are not constant?
Joe: No.
value types are constants, references types have to be null (IIRC)
Remo: Ok in that case default value => satisfied parameter, conts the same as every other parameter
so no change needed
But I think we still have poblems with the current implementation
Ian: but we have to detect them iirc
Remo: I rather think we should change the binding resolvers and askt them if they have a binding
rather than chacking for all this stuff in the heuristic checking

Ninject 2.0.1.0 not compatible with extensions.

Ninject 2.0.1.0, net-3.5

I've just hit some trouble whilst trying to upgrade to Ninject 2.0.1.0
as the extensions I'm using (Logging and Interception) both have hard
dependencies on 2.0.0.0.
I'm not sure what the best approach to dealing with minor releases
is. Is there a way that we could loosen these requirements? Could we
have a project that builds and releases all of the core extensions
built against the latest Ninject.dll?

Please remove pdb files from Nuget packages

Having the .pdb files included in Ninject's NuGet packages causes Visual Studio to think that Ninject should be included in "Just My Code." This causes the issues mentioned here, here, and here. Looking at other popular NuGet modules (Elmah, HttpModuleMagic, WebActivator, Microsoft.Web.Infrastructure, etc.), it appears that the standard convention is to not include the .pdb files.

You can set up nuget to push a special "symbols" version to symbolsource.org as described here, so that if users would like to step into Ninject code, they can configure Visual Studio to pull both the .pdb and the source files from symbolsource.org. So there should be no reason to include these files in the standard Nuget package on nuget.org.

FormatExtensions.Format throws an exception for inner classes of generic types.

FormatExtensions.Format(Type type) throws an exception on line 162 when trying to format a non-generic type that is defined inside a generic type. See attached code.

using System;
using Ninject.Infrastructure.Introspection;

namespace NinjectBugDemo
{
    class Program
    {
        static void Main(string[] args)
        {
        // This line will throw an exception.
            // It is possible to get this when doing normal bindings, this is just the minimum code to reproduce.
        typeof(Widget<int>.WidgetSomething).Format();
        }
    }


    public interface ISomeInterface<T>
    {
    }

    public class Widget<T>
    {
        public class WidgetSomething : ISomeInterface<T>
        {
        }
    }
}

What's the proper way to dispose request scoped objects

I'm using an older version (2.0) of Ninject and there is a method named DisposeRequestScoped on Ninject.Activation.Caching.Cache. However, with Ninject 2.2, that method is gone.

What's the proper way for me to dispose of objects scoped to HttpContext.Current?

Thread safety issue when multiple threads create instance of same type

Problem: We have multiple threads in our application accessing the same ASP.NET web service at the same time. The web services inherit from WebServiceBase in Ninject.Web. Randomly, the injected property was null.

A test project showed that the problem was caused by a thread safety issue in Ninject: Near simultaneous instantiation of the same type either results in an exception ("An item with the same key has already been added."), or even worse, in the injected property being null.

Here is a test program to reproduce it (on my computer, Thread.Sleep(30) results in the TestService property of AnotherService being null. Other low values result in exceptions):

using System;
using System.Threading;
using Ninject;

namespace ThreadSafetyTest
{
    internal class Program
    {
        public static IKernel Kernel { get; private set; }

        private static void Main(string[] args)
        {
            Kernel = new StandardKernel();
            Kernel.Bind<ITestService>().To<TestService>();

            for (int i = 0; i < 1000; i++)
            {
                Thread thread = new Thread(() =>
                                               {
                                                   var service = new AnotherService();

                                                   Guid guid = service.UseTheService();

                                                   Console.WriteLine(guid);
                                               });
                thread.Start();

                Thread.Sleep(30);
            }

            Console.WriteLine("Finished. Press any key to continue...");
            Console.ReadKey();
        }
    }

    public class AnotherService : InjectedBase
    {
        private ITestService testService;

        [Inject]
        public ITestService TestService
        {
            set { testService = value; }
        }

        public Guid UseTheService()
        {
            return testService.GetId();
        }
    }

    public class TestService : ITestService
    {
        private readonly Guid id = Guid.NewGuid();

        #region ITestService Members

        public Guid GetId()
        {
            return id;
        }

        #endregion
    }

    public interface ITestService
    {
        Guid GetId();
    }

    public class InjectedBase
    {
        public InjectedBase()
        {
            Program.Kernel.Inject(this);
        }
    }
}

A quick fix consists of replacing the Dictionary of the MultiMap and Planner classes with ConcurrentDictionary. That causes other problems, however: Either you have to make Ninject .NET 4.0 only, or you have to use another implementation of ConcurrentDictionary. The PLINQO project has one, but that is LGPL, and Mono of course has one in the master branch (X11 license). I tried to use that, and got it to work, but had to do some changes. Let me know if you'd like the files.

Using ConcurrentDictionary has the side effect of almost eliminating the need for locking, which should give a performance gain, especially on read operations.

Here are the changes needed (in the master branch):

Planner.cs
line 27:
private readonly Dictionary<Type, IPlan> _plans = new Dictionary<Type, IPlan>();

line 53:
return _plans.GetOrAdd(type, t =>
{
var plan = CreateEmptyPlan(type);

                                             Strategies.Map(s => s.Execute(plan));

                                             return plan;
                                         });

Multimap.cs
line 25:
private readonly ConcurrentDictionary<K, ICollection> _items = new ConcurrentDictionary<K, ICollection>();

line 37:
return _items.GetOrAdd(key, new List());

line 98:
ICollection removed;

        return _items.TryRemove(key, out removed);

Failure to access internal class constructor

I have an internal implementation of an interface that is bound to the that interface using Ninject.
The interface is public, the implementation class is internal, with a public default constructor. When trying to resolve in Silverlight via IKernel.Get, I get "Attempt by method 'DynamicClass.DynamicInjector7f4da217962e44a1a3de2308afcb08ba(System.Object[])' to access method 'MyImplentation..ctor()' failed.", but this exception is not thrown in .NET (without even applying the attribute mentioned below)?
Changing the implementation to be a public class succeeds.

I have tried using InternalsVisibleTo attribute on my implementation contained assembly, with no luck. I did apply this attribute to another assembly to test the internal implementation class is indeed accessible, and it is. Here is the property, I obtained the public key from sn.exe included with Visual Studio:

[assembly: InternalsVisibleTo("Ninject, PublicKey=002400000480000094" +
"0000000602000000240000525341310004000" +
"001000100f3fc252fdcdfdba2e6d41c88aa5d" +
"644aa480c3776f4d7a3f02625347a53fef16b" +
"3940741285b67067480cc1eda51f1a9b255cc" +
"3af2dcf77325621bd9f644de9e1311a5d2f8b" +
"d3054573da970c33566033d91c0fe4420d5b0" +
"1f996a32ae3a44fad49974edb8546f418eca5" +
"86ea085a1a175a1b79d6ec84f75d4b814a40b" +
"2abcb9")]

Note, this is using the Silverlight 4 and .NET v3.5 (non-web) version 2.2.0.0 releases

open generic double resolution

ninject version 2.2.1.0
.NET version 3.5

    public interface ISomething<T> { }

    public class StringThing : ISomething<string> { }


    var kernel = new StandardKernel();
    kernel.Bind(typeof (ISomething<>)).To(typeof (StringThing));
    var things = kernel.GetAll(typeof (ISomething<>));
    Console.WriteLine(things.Count());

This outputs 2

Shouldn't this only output 1 since it's only bound once?

Runtime error with .Net Framework 4.0

Hi, newbie here,

Maybe it is just me, everything compiled ok, and then I was getting this error message when tried to run the web application.

The error appears to be thrown at this line => Ninject.Activation.Providers.StandardProvider.Create(Ninject.Activation.IContext)

Locating source for 'c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs'. Checksum: MD5 {66 26 f5 76 56 2e 5b 67 b9 b5 aa a2 b0 f7 65 4}
The file 'c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs' does not exist.
Looking in script documents for 'c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs'...
Looking in the projects for 'c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs'.
The file was not found in a project.
Looking in directory 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\crt\src'...
Looking in directory 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\atlmfc\src\mfc'...
Looking in directory 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\atlmfc\src\atl'...
Looking in directory 'C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\atlmfc\include'...
The debug source files settings for the active solution indicate that the debugger will not ask the user to find the file: c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs.
The debugger could not locate the source file 'c:\Projects\Ninject\ninject\src\Ninject\Activation\Providers\StandardProvider.cs'.

When querying of the binding metadata expose the Implementation Type

When trying to query the metadata of the bindings in the container I am finding it very difficult to get the type that is bound to the interface.

So given

kernel.Bind<IConsumer>().To<FakeConsumer>();

How do I get the concrete type of the binding.
At the moment this is what I believe it takes.

var k = new StandardKernel();
k.Bind<IConsumer>().To<FakeConsumer>();

foreach (var binding in k.GetBindings(typeof(IConsumer)))
{
    var cb = binding.ProviderCallback;
    var req = new Request(null, typeof(IConsumer), null, () => null);
    var x = cb(new Context(k, req, null, null, null, null));
    var concrete = x.Type; //<- this is what I want
}

Loading the same modules into multiple kernels is not thread-safe.

We use multiple kernels whose modules are mostly the same, so we have an array of INinjectModules that we reuse for multiple kernels. We've seen some issues recently where kernels either have too few or too many bindings, and I was finally able to narrow this down to our reuse of individual module instances. Here's a basic repro:

void Main()
{
    var module = new FooModule(); // one module instance
    Parallel.For(1, 10000, i => {
        var kernel = new StandardKernel();
        kernel.Load(module);    // reused by multiple kernels at once.
        kernel.Get<Foo>();
    });
}

public class Foo{ public Foo(){}}
public class FooModule : NinjectModule
{
    public override void Load()
    {
        Bind<Foo>().ToSelf();
    }
}

This is testing a race condition, so you may need to run the test a few times or increase the number of repeats, but on my machine it fairly consistently produces a binding exception of one form or another.

If modules are not supposed to be reused in this way, their documentation should probably say as much, but I'm guessing this is probably just a threading issue that can easily be resolved.

Using Ninject 3.0.1.10

Race condition in GarbageCollectionCachePruner.cs

This is the issue discussed in the stackoverflow question here.

I've confirmed it still exists in the latest version, without using multi-threading. The exception will occur, occasionally, during process cleanup, in any process that creates a kernel (even a single one) and calls Dispose on that kernel. Not disposing the kernel is a workaround, but if this is the accepted answer, there should be a comment on Dispose or in the documentation at least.

Code to reproduce follows. You need to change the ProcessStartInfo to whatever you name the test console app, and possibly change the number of times to run it. For me, it happens approx. 1 in 100 processes.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Ninject;

namespace NinjectPruningRaceCondition
{
    public class WidgetService
    {}

    public static class Program
    {
        private static void RunTest()
        {
            var settings = new NinjectSettings
            {
                CachePruningInterval = TimeSpan.FromMilliseconds(1)
            };

            using (var kernel = new StandardKernel(settings))
            {
                kernel.Bind<WidgetService>().ToSelf();
                kernel.Get<WidgetService>();
            }

            Thread.Sleep(2);
        }

        static void Main(string[] args)
        {
            if(args.Length == 0)
            {
                for(int i = 0; i < 200; i++)
                {
                    var startInfo = new ProcessStartInfo("NinjectPruningRaceCondition.exe", i.ToString())
                    {
                        UseShellExecute = false
                    };
                    var process = Process.Start(startInfo);
                    process.WaitForExit();
                }
            }
            else
            {
                Console.WriteLine("Test #" + args[0]);
                RunTest();

            }
        }
    }
}

Mono - Using providers cause NullReferenceException

Kernel.Bind<IConfig>().ToProvider<ConfigProvider>();

Causes a NullReferenceException on Mono. On Windows works fine. I'm using Ninject 2.2.1.0 for mono (2.2.1.4 from nuget throws same expcetion) and Mono 2.10.5.

IConfig, DynamicConfig and ConfigProvider are simple classes. I can post them here if you want.

stacktrace:
Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object
at Ninject.Infrastructure.Language.ExtensionsForMemberInfo.GetParentDefinition (System.Reflection.MethodInfo method, BindingFlags flags) [0x00000] in :0
at Ninject.Infrastructure.Language.ExtensionsForMemberInfo.GetParentDefinition (System.Reflection.PropertyInfo property) [0x00000] in :0
at Ninject.Infrastructure.Language.ExtensionsForMemberInfo.IsDefined (System.Reflection.PropertyInfo element, System.Type attributeType, Boolean inherit) [0x00000] in :0
at Ninject.Infrastructure.Language.ExtensionsForMemberInfo.HasAttribute (System.Reflection.MemberInfo member, System.Type type) [0x00000] in :0
at Ninject.Selection.Heuristics.StandardInjectionHeuristic.ShouldInject (System.Reflection.MemberInfo member) [0x00000] in :0
at Ninject.Selection.Selector+c__AnonStorey29.<>m__4A (IInjectionHeuristic h) [0x00000] in :0
at System.Linq.Enumerable.Any[IInjectionHeuristic](IEnumerable1 source, System.Func2 predicate) [0x00000] in :0
at Ninject.Selection.Selector.m__47 (System.Reflection.PropertyInfo p) [0x00000] in :0
at System.Linq.Enumerable+c__Iterator1D1[System.Reflection.PropertyInfo].MoveNext () [0x00000] in <filename unknown>:0 at System.Collections.Generic.List1[System.Reflection.PropertyInfo].AddEnumerable (IEnumerable1 enumerable) [0x00000] in <filename unknown>:0 at System.Collections.Generic.List1[System.Reflection.PropertyInfo].AddRange (IEnumerable1 collection) [0x00000] in <filename unknown>:0 at Ninject.Selection.Selector.SelectPropertiesForInjection (System.Type type) [0x00000] in <filename unknown>:0 at Ninject.Planning.Strategies.PropertyReflectionStrategy.Execute (IPlan plan) [0x00000] in <filename unknown>:0 at Ninject.Planning.Planner+<GetPlan>c__AnonStorey28.<>m__44 (IPlanningStrategy s) [0x00000] in <filename unknown>:0 at Ninject.Infrastructure.Language.ExtensionsForIEnumerableOfT.Map[IPlanningStrategy] (IEnumerable1 series, System.Action1 action) [0x00000] in <filename unknown>:0 at Ninject.Planning.Planner.GetPlan (System.Type type) [0x00000] in <filename unknown>:0 at Ninject.Activation.Providers.StandardProvider.Create (IContext context) [0x00000] in <filename unknown>:0 at Ninject.Activation.Context.Resolve () [0x00000] in <filename unknown>:0 at Ninject.KernelBase.<Resolve>m__55 (IContext context) [0x00000] in <filename unknown>:0 at System.Linq.Enumerable+<CreateSelectIterator>c__Iterator102[Ninject.Activation.IContext,System.Object].MoveNext () [0x00000] in :0
at System.Linq.Enumerable+c__Iterator01[NInjectTest2.ConfigProvider].MoveNext () [0x00000] in <filename unknown>:0 at System.Linq.Enumerable.Single[ConfigProvider] (IEnumerable1 source, System.Func2 predicate, Fallback fallback) [0x00000] in <filename unknown>:0 at System.Linq.Enumerable.Single[ConfigProvider] (IEnumerable1 source) [0x00000] in :0
at Ninject.ResolutionExtensions.Get[ConfigProvider](IResolutionRoot root, Ninject.Parameters.IParameter[] parameters) [0x00000] in :0
at Ninject.Planning.Bindings.BindingBuilder1[NInjectTest2.IConfig].<ToProvider1>m__33[ConfigProvider](IContext ctx) [0x00000] in :0
at Ninject.Planning.Bindings.Binding.GetProvider (IContext context) [0x00000] in :0
at Ninject.Activation.Context.GetProvider () [0x00000] in :0
at Ninject.Activation.Context.Resolve () [0x00000] in :0
at Ninject.KernelBase.m__55 (IContext context) [0x00000] in :0
at System.Linq.Enumerable+c__Iterator102[Ninject.Activation.IContext,System.Object].MoveNext () [0x00000] in <filename unknown>:0 at System.Linq.Enumerable.Single[Object] (IEnumerable1 source, System.Func2 predicate, Fallback fallback) [0x00000] in <filename unknown>:0 at System.Linq.Enumerable.SingleOrDefault[Object] (IEnumerable1 source) [0x00000] in :0
at Ninject.Planning.Targets.Target1[System.Reflection.ParameterInfo].GetValue (System.Type service, IContext parent) [0x00000] in <filename unknown>:0 at Ninject.Planning.Targets.Target1[System.Reflection.ParameterInfo].ResolveWithin (IContext parent) [0x00000] in :0
at Ninject.Activation.Providers.StandardProvider.GetValue (IContext context, ITarget target) [0x00000] in :0
at Ninject.Activation.Providers.StandardProvider+c__AnonStorey3.<>m__B (ITarget target) [0x00000] in :0
at System.Linq.Enumerable+c__Iterator102[Ninject.Planning.Targets.ITarget,System.Object].MoveNext () [0x00000] in <filename unknown>:0 at System.Collections.Generic.List1[System.Object].AddEnumerable (IEnumerable1 enumerable) [0x00000] in <filename unknown>:0 at System.Collections.Generic.List1[System.Object]..ctor (IEnumerable1 collection) [0x00000] in <filename unknown>:0 at System.Linq.Enumerable.ToArray[Object] (IEnumerable1 source) [0x00000] in :0
at Ninject.Activation.Providers.StandardProvider.Create (IContext context) [0x00000] in :0
at Ninject.Activation.Context.Resolve () [0x00000] in :0
at Ninject.KernelBase.m__55 (IContext context) [0x00000] in :0
at System.Linq.Enumerable+c__Iterator102[Ninject.Activation.IContext,System.Object].MoveNext () [0x00000] in <filename unknown>:0 at System.Linq.Enumerable+<CreateCastIterator>c__Iterator01[NInjectTest2.Engine].MoveNext () [0x00000] in :0
at System.Linq.Enumerable.Single[Engine](IEnumerable1 source, System.Func2 predicate, Fallback fallback) [0x00000] in :0
at System.Linq.Enumerable.Single[Engine](IEnumerable`1 source) [0x00000] in :0
at Ninject.ResolutionExtensions.Get[Engine](IResolutionRoot root, Ninject.Parameters.IParameter[] parameters) [0x00000] in :0
at NInjectTest2.Program.Main (System.String[] args) [0x00000] in :0

Nuget update to 3.0.0-rc3

Hi there

I tried to update ninject to pre-release 3.0.0-rc3 with nuget package management console and I get this error:

Update-Package : Updating 'Ninject 2.2.1.4' to 'Ninject 3.0.0-rc3' failed. Unable to find a version of 'Ninject.Extensions.ContextPreservation' that is compatible with 'Ninject 3.0.0-rc3'.
At line:1 char:15

  • Update-Package <<<< ninject -IncludePrerelease
    • CategoryInfo : NotSpecified: (:) [Update-Package], Exception
    • FullyQualifiedErrorId : NuGetCmdletUnhandledException,NuGet.PowerShell.Commands.UpdatePackageCommand

However, this happens not for all projects in the solution that use Contextpreservation. Some of them were updated successfully?!?!

Running update a second time results in the same behaviour.

Maybe I'll spot the differences in the projects.

Cheers
Urs

Resolve WebProxy class cause NullReferenceException in mono runtime

This is my mono environment:

Mono JIT compiler version 2.10.5 (Debian 2.10.5-1)
Copyright (C) 2002-2011 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:            Included Boehm (with typed GC and Parallel Mark)

My program targets .NET Framework 4.0 and was written on Windows using Visual Studio 2011, and I was using Ninject.3.0.0.15 provided by NuGet package manager.

And I have program below works well and outputs System.Net.WebProxy

class Program {
    static void Main(string[] args) {
        Console.Write(new WebProxy())
    }
}

This should provide enough evident that I have the System.Net.WebProxy class in mono environment, but code below throws a NullReferenceException:

class Program {
    static void Main(string[] args) {
        IKernel kernel = new StandardKernel();
        kernel.Bind<WebProxy>().ToSelf();
        Console.WriteLine(kernel.Get<WebProxy>());
    }
}

The full stachtrace is:

Unhandled Exception: System.NullReferenceException: Object reference not set to an instance of an object
  at Ninject.Infrastructure.Language.ExtensionsForMemberInfo.get_ParentDefinitionMethodInfo () [0x00000] in <filename unknown>:0 
  at Ninject.Infrastructure.Language.ExtensionsForMemberInfo.GetParentDefinition (System.Reflection.MethodInfo method, BindingFlags flags) [0x00000] in <filename unknown>:0 
  at Ninject.Infrastructure.Language.ExtensionsForMemberInfo.GetParentDefinition (System.Reflection.PropertyInfo property) [0x00000] in <filename unknown>:0 
  at Ninject.Infrastructure.Language.ExtensionsForMemberInfo.IsDefined (System.Reflection.PropertyInfo element, System.Type attributeType, Boolean inherit) [0x00000] in <filename unknown>:0 
  at Ninject.Infrastructure.Language.ExtensionsForMemberInfo.HasAttribute (System.Reflection.MemberInfo member, System.Type type) [0x00000] in <filename unknown>:0 
  at Ninject.Selection.Heuristics.StandardInjectionHeuristic.ShouldInject (System.Reflection.MemberInfo member) [0x00000] in <filename unknown>:0 
  at Ninject.Selection.Selector+<>c__DisplayClass3.<SelectPropertiesForInjection>b__2 (IInjectionHeuristic h) [0x00000] in <filename unknown>:0 
  at System.Linq.Enumerable.Any[IInjectionHeuristic] (IEnumerable`1 source, System.Func`2 predicate) [0x00000] in <filename unknown>:0 
  at Ninject.Selection.Selector.<SelectPropertiesForInjection>b__1 (System.Reflection.PropertyInfo p) [0x00000] in <filename unknown>:0 
  at System.Linq.Enumerable+<CreateWhereIterator>c__Iterator35`1[System.Reflection.PropertyInfo].MoveNext () [0x00000] in <filename unknown>:0 
  at System.Collections.Generic.List`1[System.Reflection.PropertyInfo].AddEnumerable (IEnumerable`1 enumerable) [0x00000] in <filename unknown>:0 
  at System.Collections.Generic.List`1[System.Reflection.PropertyInfo].AddRange (IEnumerable`1 collection) [0x00000] in <filename unknown>:0 
  at Ninject.Selection.Selector.SelectPropertiesForInjection (System.Type type) [0x00000] in <filename unknown>:0 
  at Ninject.Planning.Strategies.PropertyReflectionStrategy.Execute (IPlan plan) [0x00000] in <filename unknown>:0 
  at Ninject.Planning.Planner+<>c__DisplayClass1.<CreateNewPlan>b__0 (IPlanningStrategy s) [0x00000] in <filename unknown>:0 
  at Ninject.Infrastructure.Language.ExtensionsForIEnumerableOfT.Map[IPlanningStrategy] (IEnumerable`1 series, System.Action`1 action) [0x00000] in <filename unknown>:0 
  at Ninject.Planning.Planner.CreateNewPlan (System.Type type) [0x00000] in <filename unknown>:0 
  at Ninject.Planning.Planner.GetPlan (System.Type type) [0x00000] in <filename unknown>:0 
  at Ninject.Activation.Providers.StandardProvider.Create (IContext context) [0x00000] in <filename unknown>:0 
  at Ninject.Activation.Context.Resolve () [0x00000] in <filename unknown>:0 
  at Ninject.KernelBase+<>c__DisplayClass10.<Resolve>b__c (IBinding binding) [0x00000] in <filename unknown>:0 
  at System.Linq.Enumerable+<CreateSelectIterator>c__Iterator27`2[Ninject.Planning.Bindings.IBinding,System.Object].MoveNext () [0x00000] in <filename unknown>:0 
  at System.Linq.Enumerable+<CreateCastIterator>c__Iterator17`1[System.Net.WebProxy].MoveNext () [0x00000] in <filename unknown>:0 
  at System.Linq.Enumerable.Single[WebProxy] (IEnumerable`1 source, System.Func`2 predicate, Fallback fallback) [0x00000] in <filename unknown>:0 
  at System.Linq.Enumerable.Single[WebProxy] (IEnumerable`1 source) [0x00000] in <filename unknown>:0 
  at Ninject.ResolutionExtensions.Get[WebProxy] (IResolutionRoot root, Ninject.Parameters.IParameter[] parameters) [0x00000] in <filename unknown>:0 
  at PingApp.Schedule.Program.Main (System.String[] args) [0x00000] in <filename unknown>:0 

I found other class (such as Program class itself) works well with NInject, currently the only exception is System.Net.WebProxy class. Since I didn't see any .ctor calls in the stacktrace, it doesn't seem a problem with constructor selection, so any idea how to solve this problem?

2 ctors with [Inject] should result in Exception

According to the documentation "If a constructor has an [Inject] attribute, it is used. If multiple constructors have an [Inject] attribute, Ninject will throw a NotSupportedException."

I have this test that is currently failing:

    [Fact]
    public void TwoInjectsOnDifferentContructorsWillResultInException()
    {
        var kernel = new StandardKernel();

        Assert.Throws<NotSupportedException>(
            delegate{
                         kernel.Get<TwoInjectedConstructorsThrows>();
                     }
        );

    }

    public class TheOneRing {}
    public class TheDarkCrystal {}

public class TwoInjectedConstructorsThrows
{
    [Inject]
    public TwoInjectedConstructorsThrows(TheOneRing ring)
    {
        Console.WriteLine("ring");
    }

    [Inject]
    public TwoInjectedConstructorsThrows(TheDarkCrystal rock)
    {
        Console.WriteLine("rock");
    }
}

the output shows that the ring constructor was called.

Ctors are not picked in the right order

 Greetings,
Accoding to the documentation on the github wiki ctor injection

should choose based on:
If a constructor has an [Inject] attribute, it is used.
If no constructors have an [Inject] attribute, Ninject will select the
one with the most parameters that Ninject understands how to resolve.
If no constructors are defined, Ninject will select the default
parameterless constructor.
However I found that this unit test fails. Is this a bug? I found a
similar thread from last spring but there was no resolution.

 [Test] 
 public void NoParamCtorShouldBeUsed(){ 
        var dojo = new StandardKernel(); 
        Assert.That(dojo.Get< Foo>().NoParamCtorUsed, Is.True); 
 } 

  public class Foo 
    { 
        public bool NoParamCtorUsed; 
        public bool AmNothingWasUsed; 
        public Foo(IAmNothing nothing) 
        { 
            AmNothingWasUsed = true; 
        } 
        public Foo() 
        { 
            NoParamCtorUsed = true; 
        } 
    } 
    public interface IAmNothing {} 

If I reverse the physical order of the ctors in the class then the
test passes.

injection in fields does not work in rc3

Try the following example:

using System;
using Ninject;

namespace Tester
{
    public interface IFooService
    {
    }

    public interface IBarService
    {
        IFooService FooService
        {
            get;
        }
    }

    public class FooService : IFooService
    {
    }

    public class BarService : IBarService
    {
        [Inject]
        private IFooService _fooService;

        public IFooService FooService
        {
            get
            {
                return _fooService;
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            NinjectSettings settings = new NinjectSettings()
            {
                InjectNonPublic = true,
                InjectParentPrivateProperties = true,
            };
            StandardKernel kernel = new StandardKernel(settings);
            kernel.Bind<IFooService>().To<FooService>();
            kernel.Bind<IBarService>().To<BarService>();
            Console.WriteLine(
                "IBarService.FooService != null: " +
                (kernel.Get<IBarService>().FooService != null)
            );

        }
    }
}

Named typed bindings not working on multi-level injections

Allright, that one is not exactly easy to find a title for ;)

I am using a name-constraint binding for a type, let's say ITypeA :

kernel.Bind().ToConstant(new TypeA()).Named("myNamedConstraint");

if I try to do a
kernel.Get(typeof(ITypeA), "myNamedConstraint")
everything is fine

now, if ITypeA is a constructor-injection dependency for ITypeB

TypeB( ITypeA dependency )

and that I do a

kernel.Get(typeof(TypeB), "myNamedConstraint")

it won't work.

and finally, if I do not specify the name constraint (and only one registration of ITypeA has been done ):

kernel.Get(typeof(TypeB))

it works !!

it makes me think that the named constraint are only considered when Getting the bound types at the first level, and it's not propagated to get the instances of the bound types if they're implied by a constructor injection.

I hope you can reproduce this, don't hesitate to contact me for any question.

EDIT : I'm using Version 2.2.0.0 for Windows Phone 7

Named syntax returns wrong interface

Named currently returns IBindingWithSyntax instead of
IBindingWithOrOnSyntax which makes it impossible to define a named
binding with an activation action without defining an always true When
condition.

InjectNonPublic Kernel Not Injecting Non-Public Members In Base Classes

Ninject isn't injecting non-public members in base classes. Try the following example:

internal class Program
{
    public static void Main()
    {
        var settings = new NinjectSettings
                       {
                           InjectNonPublic = true
                       };
        var kernel = new StandardKernel(settings);

        kernel.Bind<ISomeInterface>().To<SomeInterfaceImplementation>().InTransientScope();
        kernel.Bind<InjectMe>().ToSelf();
        kernel.Bind<InjectMeChild>().ToSelf();

        if (kernel.TryGet<InjectMe>().PublicPrivateProperty == null)
        {
            throw new InvalidOperationException("PublicPrivateProperty not injected in InjectMe instance.");
        }
        if (kernel.TryGet<InjectMeChild>().PublicPrivateProperty == null)
        {
            throw new InvalidOperationException("PublicPrivateProperty not injected in InjectMeChild instance.");
        }
    }
}

public interface ISomeInterface
{
}

public sealed class SomeInterfaceImplementation : ISomeInterface
{
}

public class InjectMe
{
    [Inject]
    public ISomeInterface PublicPrivateProperty
    {
        get;
        private set;
    }
}

public class InjectMeChild : InjectMe
{
}

You should get the second exception throwing; I'd expect neither exception to throw. If you make the PublicPrivateProperty setter public then no exceptions are thrown.

NinjectSettings.InjectParentPrivateProperties odd behavior

Getting an instance of TestClassDerived throws Ninject.ActivationException:

Error activating float
No matching bindings are available, and the type is not self-bindable.
Activation path:
  2) Injection of dependency float into property Value of type TestClass
  1) Request for TestClassDerived

Code:

using System;
using Ninject;

public class TestClass
{
    // making this property 'public' removes the error
    float Value
    {
        // !! Don't overlook that there is no "set" and no "[Inject]" !!
        get { return 0f; }
    }
}

public class TestClassDerived : TestClass
{ }

static class Program
{
    static void Main()
    {
        var kernel = new StandardKernel( new NinjectSettings
        {
            UseReflectionBasedInjection = true,

            // setting any of these to 'false' removes the error
            InjectNonPublic = true,
            InjectParentPrivateProperties = true,
        } );

        // SUCCESS
        KernelTest<TestClass>( kernel );

        // ERROR
        KernelTest<TestClassDerived>( kernel );
    }

    static void KernelTest<T>( StandardKernel kernel )
    {
        try
        {
            WriteLine( ConsoleColor.White, "StandardKernel.Get<" + typeof( T ).Name + ">();" );

            kernel.Get<T>();

            WriteLine( ConsoleColor.Green, "SUCCESS" );
        }
        catch ( Exception e )
        {
            WriteLine( ConsoleColor.DarkRed, e );
        }

        Console.WriteLine();
    }

    static void WriteLine( ConsoleColor color, object value )
    {
        Console.ForegroundColor = color;
        Console.WriteLine( value );
    }
}

My workaround is to set NinjectSettings.InjectParentPrivateProperties to false.
Maybe I don't understand InjectParentPrivateProperties's behavior, but the circumstance that Ninject tries to inject into a private get-only property, but not into a public get-only property does not seem right ;)

Thread Safety Issue

The only related thread is
http://groups.google.com/group/ninject/browse_thread/thread/a0f0f87a6fef89d2.
I have a problem with thread safety of ninject when using
StandardKernel for resolving instances of the same class in multiple
threads. I am using binding to a concrete type:


Bind().ToSelf().InTransientScope();

All calls to ninject are encapsulated in static InstanceActivator
class (there is no thread synchronization mechanisms used in it). When
trying to resolve an instance of SomeClass in several concurrent
threads like this:


static void Main(string[] args)
               {
                       for (int i = 0; i < 10; i++)
                       {
                               new Thread(() =>
                                               {
                                                       try
                                                       {

Console.WriteLine(InstanceActivator.Resolve().GetTicks());
                                                       }
                                                       catch (Exception e)
                                                       {
                                                                       Console.WriteLine(e.ToString());
                                                       }

                                               }).Start();
                       }
                       Console.ReadLine();
               }

whose implementation is:


public static T Resolve()
               {
                       //lock (Container)
                       //{
                               return Container.Get();
                       //}
               }

I always obtain an ArgumentException "An item with the same key has
already been added." Stack trace:


 at System.ThrowHelper.ThrowArgumentException(ExceptionResource
resource)
  at System.Collections.Generic.Dictionary`2.Insert(TKey key, TValue
value, Boolean add)
  at System.Collections.Generic.Dictionary`2.Add(TKey key, TValue
value)
  at Ninject.Components.ComponentContainer.CreateNewInstance(Type
component, Type implementation)
  at Ninject.Components.ComponentContainer.ResolveInstance(Type
component, Type implementation)
  at Ninject.Components.ComponentContainer.d__0.MoveNext()
  at System.Linq.Enumerable.d__aa`1.MoveNext()
  at System.Linq.Enumerable.d__14`2.MoveNext()
  at System.Linq.Enumerable.Any[TSource](IEnumerable`1 source)
  at Ninject.KernelBase.CanResolve(IRequest request)
  at Ninject.KernelBase.Resolve(IRequest request)
  at
Ninject.ResolutionExtensions.GetResolutionIterator(IResolutionRoot
root, Type service, Func`2 constraint, IEnumerable`1 parameters,
Boolean isOptional, Boolean isUnique)
  at Ninject.ResolutionExtensions.Get[T](IResolutionRoot root,
IParameter[] parameters)
  at TestNinject.InstanceActivator.Resolve[T]() in C:\Tests
\TestNinject\TestNinject\InstanceActivator.cs:line 23
  at TestNinject.Program.b__0() in C:\Tests\TestNinject
\TestNinject\Program.cs:line 19

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.