我的类(class)结构是:
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;
}
}
我的 Ninject 绑定(bind)是这样的:
var kernel = new StandardKernel();
kernel.Bind<IPhotoService>().To<PhotoService>();
kernel.Bind<IRepository>().To<Repository>();
kernel.Bind<DTConfig>().ToSelf();
现在我想要的是在创建 PhotoService
实例时将accountId
作为参数传递
var photo = kernel.Get<IPhotoService>();
如何在创建 PhotoService 实例时将参数传递给 DTConfig。 accountId 从服务中获取,在编译时不可用。
如果需要任何其他信息,请随时发表评论。
最佳答案
Ninject 中有一个ConstructorArgument
的概念,它允许您传递仅在运行时已知的变量。典型的例子是:
var photoService = kernel.Get<IPhotoService>(new ConstructorArgument("accountId", <your value here>));
现在需要注意的是,这只会深入一个级别。然而,有一个接受名为 shouldInherit
的 bool 标志的构造函数,它允许您的值在解析具体类型时传播给 child :
var photoService = kernel.Get<IPhotoService>(new ConstructorArgument("accountId", <your value here>, shouldInherit:true));
关于.net - 如何使用 Ninject 在依赖链下传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28745332/