Ninject - binding constructors with arguments / Entity Framework connection string

后端 未结 2 772
广开言路
广开言路 2021-02-18 16:56

Please forgive my ignorance, but I am very new to IOC and NinJect. I have searched for high and low for easily understandable solutions but so far they have eluded me.

S

相关标签:
2条回答
  • 2021-02-18 17:15

    Newer versions of Ninject allow to get rid of magic strings in the binding definition. Something like this:

    public class StandardModule : NinjectModule
    {
        public override void Load()
        {
            string connectionString = "...";
            Bind<IMyEntityFrameWorkRepository()
                .ToConstructor(_ => new MyEntityFrameWorkRepository(connectionString);
        }
    }
    

    For bindings involving generic types (e.g. bind ISomeService<T> to SomeService<T> and binding should be performed for all possible types at once), ToConstructor cannot be used (a new expression is required), so WithConstructorArgument remains the simplest approach. E.g.:

    Bind(typeof(ISomeService<>))
        .To(typeof(SomeService<>))
        .WithConstructorArgument("someParam", "someValue");
    
    0 讨论(0)
  • 2021-02-18 17:24

    You can use the .WithConstructorArgument() method to specify constructor arguments. The first argument should be the name of the constructor parameter.

    public class StandardModule : NinjectModule
    {
        public override void Load()
        {
            string connectionString = "...";
            Bind<IMyEntityFrameWorkRepository().To<MyEntityFrameWorkRepository>()
                .WithConstructorArgument("sqlConnectionString", connectionString);
        }
    

    }

    0 讨论(0)
提交回复
热议问题