Ninject - binding constructors with arguments / Entity Framework connection string

人走茶凉 提交于 2019-12-03 22:35:55
mrydengren

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);
    }

}

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");
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!