.net - 如何使用 Ninject 在依赖链下传递参数

标签 .net c#-4.0 ninject

我的类(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/

相关文章:

c# - 在 react 性管道中管理状态

c# - 以流格式保存图片框中的图像

c# - Ninject Constructor 参数检查参数是否存在

asp.net-mvc - 与 Ninject 的集成测试

.net - NHibernate,每个演示者的 ISession,多个演示者打开

c# - c# 中 object[] 的当前方法参数

asp.net - 生产服务器上的 "aspnet_regiis -i"有多安全?

c# - ConcurrentDictionary<TKey,TValue> 与 Dictionary<TKey,TValue>

asp.net-mvc-3 - 使用存储库模式获取最后插入的行 ID

c# - 在 .Net 3.5 中使用 Ninject 时 System.Core 的 System.Io.FileNotFoundException