Ninject Get <T> with constructor argument

Here is my module:

public class LoggerModule : NinjectModule
{
    public override void Load()
    {
        Bind<ILogger>().To<NLogLogger>()
            .WithConstructorArgument(
                typeof(Type),
                x => x.Request.ParentContext.Plan.Type);
    }
}

So, as you can see, NLogLoggerexpects to Typebe passed to the constructor.

This is my Unit Test:

    [Test]
    public void ResolveLoggerDependency()
    {
        var module = new LoggerModule();
        var kernal = new StandardKernel(module);
        var service = kernal.Get<ILogger>(new ConstructorArgument("type", typeof(int)));
        Assert.That(service, Is.Not.Null);
    }

It throws a null reference error on kernal.Get<ILogger>, so I can only assume that I am not passing the constructor value correctly. How to transfer when using Get<T>?

+4
source share
2 answers

So this question seems to relate to your other question .

The requirement in this matter was to introduce into the NLogLoggertype of object into which it will be introduced.

, ILogger , . , , ILogger.

, unit test , . :

, :

public class TestClass
{
    private readonly ILogger m_Logger;

    public TestClass(ILogger logger)
    {
        m_Logger = logger;
    }

    public ILogger Logger
    {
        get { return m_Logger; }
    }
}

:

[Test]
public void ResolveLoggerDependency()
{
    var module = new LoggerModule();
    var kernal = new StandardKernel(module);
    var test_object = kernal.Get<TestClass>();
    Assert.That(test_object.Logger, Is.Not.Null);
}

, NLogLogger TestClass NLog. Reflection, .

+3

Bind<ILogger>().To<NLogLogger>();

-1

Source: https://habr.com/ru/post/1616502/


All Articles