Skip to content

.Net 6 + Ninject 3.3.4: InvalidProgramException when using delegates for initializing constructor parameters #389

@nschuessler

Description

@nschuessler

Given the simplified repro below, the following code throws InvalidProgramException on the delegate used to create the eventId parameter (marked). This works with .Net 5.0.

Any tips what to do here?

The code:

namespace Example
{
    using Ninject;
    using Ninject.Modules;
    using System;
    using System.Collections.Generic;

    public class Program
    {
        public static void Main()
        {
            MessageModule messageModule = new MessageModule();
            StandardKernel standardKernel = new StandardKernel(messageModule);
            IMessageProcessor processor = standardKernel.Get<IMessageProcessor>();
        }
    }
    public class MessageModule : NinjectModule
    {
        public override void Load()
        {
            this.Bind<string>().ToConstant("event-id-constant").Named("EventId");
            this.Bind<string>().ToConstant("event-type-constant").Named("EventType");
            this.Bind<IMessage>().ToConstant(new DoNothingMessage());

            Action<IMessageEvent> e = (IMessageEvent evt) => { };
            this.Bind<Action<IMessageEvent>>().ToConstant(e);

            this.Bind<IDictionary<string, string>>().ToConstant(new Dictionary<string, string>()).Named("LoggingProperties");

            this.Bind<IMessageProcessor>()
                .To<MessageProcessor>()
                .WithConstructorArgument(
                    "eventId",
                    // *** InvalidProgramException here:
                    context => { return context.Kernel.Get<string>("EventId"); })
                .WithConstructorArgument(
                    "eventType",
                    context => { return context.Kernel.Get<string>("EventType"); })
                .WithConstructorArgument(
                    "loggingProperties",
                    context => { return context.Kernel.Get<IDictionary<string, string>>("LoggingProperties"); });
        }
    }

    public interface IMessageProcessor
    {
    }

    public interface IMessage
    {
    }

    public interface IMessageEvent
    {
    }

    public class MessageProcessor : IMessageProcessor
    {
        public MessageProcessor(
            string eventId,
            string eventType,
            IMessage message,
            Action<IMessageEvent> onMessageEventCreated,
            IDictionary<string, string> loggingProperties)
        {

        }
    }

    public class DoNothingMessage : IMessage { }
    public class DoNothingMessageEvent : IMessageEvent { }
}

Metadata

Metadata

Assignees

Labels

Type

No type
No fields configured for issues without a type.

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions