使用字符串,反模式进行依赖注入(ninject)? [英] Dependency injection (ninject) using strings, anti-pattern?
问题描述
我有一些使用ninject注入依赖项的代码,这些依赖项是实际的字符串。例如,这是注入字符串而不是创建新对象的反模式。
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.
即我想注入用户名和密码,实际上会更好的方法是创建一个具有凭据的小类,其中包含Usernamd和Password的2种属性,然后注入它吗?
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);
此代码闻到了吗?
任何
推荐答案
我宁愿使用 ToMethod()
I would prefer to use ToMethod()
here:
kernel.Bind<IUser>()
.ToMethod(ctx => new User(configuration.Username, configuration.Password));
如果 User
构造函数还具有其他依赖项,
If the User
constructor has other dependencies, then I would defer to @jgauffin's answer.
您仍然可以将 ToMethod()
与内核
:
kernel.Bind<IUser>()
.ToMethod(ctx => new User(configuration.Username,
configuration.Password,
ctx.Kernel.Get<Foo>()));
这篇关于使用字符串,反模式进行依赖注入(ninject)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!