Question

Please see the sample code below. Its an over simplified scenario to demonstrate a problem I am encountering when binding using the WhenInjectedInto method. This has always worked with the earlier version of ninject. But some how with this upgrade to 3.0 I can't see where is the problem. I am getting a cyclic dependency exception (i.e. the decorator is being injected into itself) when I shouldn't be getting that one if the WhenInjectedInto method gets applied properly.

Please also note, this is an oversimplified scenario, hence the classes and interfaces follow convention, so possibly for this code sample a solution can be achieved using default conventions with a lot less ioc code, but bare in mind for my actual scenario I won't have classes and interfaces follow conventions so fluently.

using System;
using System.Collections.Generic;
using System.Linq;
using NUnit.Framework;
using Ninject.Extensions.Conventions;
using Ninject.Extensions.Conventions.BindingGenerators;
using Ninject.Syntax;

namespace Ninject.Usage.Spike
{
public class ElderlyPerson : IPerson
{
    private readonly IPerson _actual;

    public ElderlyPerson(IPerson actual)
    {
        _actual = actual;
    }

    public string Name { get { return string.Format("Sir {0}", _actual.Name); } }
}

public class Person : IPerson
{
    public string Name { get; protected set; }
}

public interface IPerson { string Name { get; } }

[TestFixture]
public class Class1
{
    [Test]
    public void Test()
    {
        using(var k = new StandardKernel())
        {
            k.Bind<IPerson>().To<ElderlyPerson>().InSingletonScope();
            k.Bind(x => x.FromThisAssembly()
                            .SelectAllClasses()
                            .Where(t => t.IsAssignableFrom(typeof (IPerson)))
                            .BindWith<MyGenerator>()
                            .Configure(c => c.WhenInjectedInto<ElderlyPerson>().InSingletonScope()));

            var person = k.Get<IPerson>();
            Assert.That(person.Name, Is.StringContaining("Sir"));
        }
    }
}

public class MyGenerator : IBindingGenerator
{
    public IEnumerable<IBindingWhenInNamedWithOrOnSyntax<object>> CreateBindings(Type type, IBindingRoot bindingRoot)
    {
        return type == typeof(ElderlyPerson) 
            ? Enumerable.Empty<IBindingWhenInNamedWithOrOnSyntax<object>>() 
            : new[] { bindingRoot.Bind(typeof(IPerson)).To(type) };
    }
}
}
Was it helpful?

Solution

Your Where condition is wrong! You can't assign IPerson to Person. Switch the arguments.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top