无法在构造函数中使用 Unity 依赖项

Cannot use Unity dependency in constructor

我 运行 遇到了一个我似乎找不到解决方案的问题,仅仅是因为我不明白如何修复此 NullReferenceException。

我有我的构造函数;

public MainViewModel()
{
    this.Refresh = new DelegateCommand(this.DoRefresh);
    //...More like this...
    //...and finally...
    this.InitializeObjects();
}

然后属性之间的某处存在依赖关系

[Dependency]
public IUnityContainer Container { get; set; }

最后是在 'Container'

上生成 NullReferenceException 的 InitializeObjects 方法
private void InitializeObjects()
{
using (var context = this.Container.Resolve<IDbContextScope>())
{
    //...remainder of the method...
}
}

异常抛出在这段代码的第3行,'using (var ...'

开头的行

异常是 ArgumentNullException;

Message "Value cannot be nul.Parameter name: container"
Source = Microsoft.Practices.Unity
StackTrace = at Microsoft.Practices.Unity.UnityContainerExtensions.Resolve....etc..

所以我的具体问题是; 确实是 IUnityContainer Container 抛出了异常吗? 为什么会抛出异常? 我该如何解决这个问题?

编辑:

正如在 post 下的前 2/3 评论中所发现的那样,断言了 NullReferenceException 的原因。但是,我仍然不知道如何解决它,因为我没有将其作为您的日常 NRE。需要 Container 的函数用于初始化程序运行所需的值,因此需要在构造函数内部调用。据我所知,我不能只声明依赖关系,所以我该如何解决这个问题..?

像这样的依赖属性的问题

[Dependency]
public IUnityContainer Container { get; set; }

它们在构造函数中不可用。如果必须在构造函数中使用此值,请使用构造函数依赖项

public MainViewModel(IUnityContainer muhContainer, SomeOtherDependency derp)
{
    // use muhContainer and derp here
}

一般来说,如果你的对象必须有一个依赖项,它应该通过构造函数注入来提供。如果您的依赖项具有可接受的默认值,但您可能希望在运行时通过配置进行更改,那么 属性 注入就可以了。

[Dependency]
public Herp WhoCares 
{
    get { return _herp ?? _defaultHerpDoesntMatterLol; }
    set { _herp = value; }
}