Ans*_*tia 2 .net ninject c#-4.0
我的班级结构是:
public class PhotoService {
private IRepository _repo;
private DTConfig _config;
public PhotoService(IRepository repo, DTConfig config)
{
_repo = repo;
_config = config;
}
}
public class DTConfig
{
private int _accountId;
public DTConfig(int accountId)
{
_accountId = accountId;
}
}
Run Code Online (Sandbox Code Playgroud)
我的 Ninject 绑定是这样的:
var kernel = new StandardKernel();
kernel.Bind<IPhotoService>().To<PhotoService>();
kernel.Bind<IRepository>().To<Repository>();
kernel.Bind<DTConfig>().ToSelf();
Run Code Online (Sandbox Code Playgroud)
现在我想要的是accountId在创建PhotoService实例时将其作为参数传递
var photo = kernel.Get<IPhotoService>();
Run Code Online (Sandbox Code Playgroud)
如何在创建 PhotoService 实例时将参数传递给 DTConfig。accountId 是从服务中获取的,在编译时不可用。
如果需要任何其他信息,请随时发表评论。
ConstructorArgumentNinject中有 a 的概念,它允许您传递仅在运行时已知的变量。典型的例子是:
var photoService = kernel.Get<IPhotoService>(new ConstructorArgument("accountId", <your value here>));
Run Code Online (Sandbox Code Playgroud)
现在有了这个需要注意的是,这只是去一个级别深度。然而,有一个构造函数接受一个名为 的 bool 标志shouldInherit,它允许您的值在解析具体类型时传播到子代:
var photoService = kernel.Get<IPhotoService>(new ConstructorArgument("accountId", <your value here>, shouldInherit:true));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1827 次 |
| 最近记录: |