Search code examples
c#dependency-injectionninject

Dependency injection (ninject) using strings, anti-pattern?


I have some code that is using ninject to inject dependencies, these dependencies are actual strings. Is this an anti-pattern to inject strings rather than creating a new object for example.

I.e. I wanted to inject Username and Password, would it actually be better to create a small class called credentials with 2 properies of Usernamd and Password and inject this ?

Injecting strings into constructors can be done via

kernel.Bind<IUser>().To<User>()
      .WithConstructorArgument(@"username", configuration.Username)
      .WithConstructorArgument(@"password", configuration.Password);

Is this code smell ?

Any ideas or improvement on what I am doing ?


Solution

  • I would prefer to use ToMethod() here:

    kernel.Bind<IUser>()
          .ToMethod(ctx => new User(configuration.Username, configuration.Password));
    

    If the User constructor has other dependencies, then I would defer to @jgauffin's answer.

    You could still use ToMethod() with Kernel:

    kernel.Bind<IUser>()
          .ToMethod(ctx => new User(configuration.Username,
                                    configuration.Password,
                                    ctx.Kernel.Get<Foo>()));