通过 Unity 解析对象时出现异常 "Value cannot be null"

Getting exception "Value cannot be null" while resolving an object by Unity

我在使用 Unity 容器解析对象时遇到异常:

Message "Value cannot be null.\r\nParameter name: container" Source "Microsoft.Practices.Unity" string

我有一个 Prism 应用程序,其中我有 ServiceModuleServiceModule 只有接口及其实现:

public interface ICommonService
{
    string SomeStorage { get; set; }        
}

public class CommonService : ICommonService
{
    string fooStorage=DateTime.Now.ToString();
    public string FooStorage
    {
        get
        {
           return fooStorage;
        }
        set
        {
            fooStorage = value;
            OnPropertyChanged("FooStorage");                                
        }
    }
}

我在 ModuleAViewModelA 中创建了一个 ICommonService 实例。它工作正常:

unityContainer = new UnityContainer();
unityContainer.RegisterType<ICommonService, CommonService>(new ContainerControlledLifetimeManager());
IMyService someFoo = unityContainer.Resolve<ICommonService>();
someFoo.FooStorage = "AAAOOOBBB";

然后我想在ModuleBviewModelB中读取这个数据。这段代码抛出异常:

ICommonService someFoo = unityContainer.Resolve<ICommonService>();
string str=someFoo.FooStorage;

例外说:

Message "Value cannot be null.\r\nParameter name: container" Source "Microsoft.Practices.Unity" string

我做错了什么?任何帮助将不胜感激!

根据您收到的错误消息,unityContainer 的值很可能是 null。确保正确初始化它。