我花了几个小时试图解决这个问题,但没有运气。我使用unity在我的SSPResourceManagerWrapper类中注入我的_translation属性,该类返回null而不是translationService对象。
注册依赖当应用程序开始注册所有依赖项时,会调用UIbootstrapper类。并在创建控制器对象时解决。
public class UiBootstrapper
{
public static IUnityContainer RegisterUiComponents(IUnityContainer container)
{
container.RegisterType<SSPResourceManagerWrapper>();
container.RegisterType<SSPResourceManager>();
container.RegisterType<ITranslationService, TranslationService>();
return container;
}
_translation属性在此处返回null。而不是translationService对象
public class SSPResourceManager
{
private static ITranslationService _translationService;
private static string _languageCode =
System.Web.HttpContext.Current.Session["LanguageCode"].ToString();
// constructor injection
public SSPResourceManager(ITranslationService translationService)
{
_translationService = translationService;
}
public static string SSP_Validation_Required
{
get
{
return _translationService.Read("SSP_Validation_Required", "SSP", _languageCode);
}
}
}
使用SSPResourceManager的地方
public abstract class AddressVM
{
[Required(ErrorMessageResourceType = typeof(SSPResourceManager), ErrorMessageResourceName
= "SSP_Validation_Required")]
[StringLength(50)]
public string Name { get; set; }
}
答案 0 :(得分:3)
您正在创建自己的SSPResourceManagerWrapper
实例,而不是使用Unity容器解析它:
private static ITranslationService _translationService =
new SSPResourceManagerWrapper()._translation;
容器永远没有机会提供依赖项。尝试使用Resolve
:
private static ITranslationService _translationService =
container.Resolve<SSPResourceManagerWrapper>()._translation;
甚至更好:
private static ITranslationService _translationService =
container.Resolve<ITranslationService>();