Mar*_*tin 8 c# dependency-injection ninject
我有一些代码使用ninject来注入依赖项,这些依赖项是实际的字符串.这是注入字符串的反模式,而不是例如创建新对象.
即我想注入用户名和密码,实际上更好的是创建一个名为凭证的小类,其中有两个属性的Usernamd和密码并注入此内容?
将字符串注入构造函数可以通过
kernel.Bind<IUser>().To<User>()
.WithConstructorArgument(@"username", configuration.Username)
.WithConstructorArgument(@"password", configuration.Password);
Run Code Online (Sandbox Code Playgroud)
这个代码有异味吗?
我正在做什么的任何想法或改进?
我更喜欢在ToMethod()这里使用:
kernel.Bind<IUser>()
.ToMethod(ctx => new User(configuration.Username, configuration.Password));
Run Code Online (Sandbox Code Playgroud)
如果User构造函数有其他依赖关系,那么我会推迟到@ jgauffin的答案.
您还可以使用ToMethod()带Kernel:
kernel.Bind<IUser>()
.ToMethod(ctx => new User(configuration.Username,
configuration.Password,
ctx.Kernel.Get<Foo>()));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3093 次 |
| 最近记录: |