C# 使用惰性类型时如何注入参数?
我有一个Translation类,它接受C# 使用惰性类型时如何注入参数?,c#,unity-container,lazy-evaluation,C#,Unity Container,Lazy Evaluation,我有一个Translation类,它接受ITranslationService作为它的参数。注册Lazy类型时如何注入翻译服务?这就是我到目前为止所做的,但是运气不好 public class Translation { public Translation(ITranslationService translationService) { // code here } } container.RegisterType<ITranslationSe
ITranslationService
作为它的参数。注册Lazy
类型时如何注入翻译服务?这就是我到目前为止所做的,但是运气不好
public class Translation
{
public Translation(ITranslationService translationService)
{
// code here
}
}
container.RegisterType<ITranslationService, TranslationService>();
container.RegisterType<Lazy<Translation>>(new InjectionConstructor(typeof(ITranslationService)));
公共类翻译
{
公共翻译(ITranslationService translationService)
{
//代码在这里
}
}
container.RegisterType();
RegisterType(新注入构造函数(typeof(ITranslationService));
尝试解析Lazy
类型时出现错误消息:
延迟初始化的类型没有公共的、无参数的
建造师
Unity支持惰性,但您必须对其进行配置:
unityContainer.AddNewExtension<LazySupportExtension>();
unityContainer.AddNewExtension();
那就不要做
container.RegisterType<Lazy<Translation>(new InjectionConstructor(typeof(ITranslationService)));
container.RegisterTypeUnity支持Lazy
,但您必须对其进行配置:
unityContainer.AddNewExtension<LazySupportExtension>();
unityContainer.AddNewExtension();
那就不要做
container.RegisterType<Lazy<Translation>(new InjectionConstructor(typeof(ITranslationService)));
container.RegisterType首先,解析Lazy
(请参阅新增部分),因此您不需要做任何特殊操作,只需注册iTransationService
,就可以解析Lazy
因此,以下仅适用于Unity 2
- 您可以从Piotr Wlodek安装。然后,您需要使用以下方法启用它:
container.AddNewExtension<LazySupportExtension>();
首先,解决懒惰问题(请参阅“新增内容”一节),因此您不需要做任何特殊的事情,只需注册ITranslationService
,就可以解决懒惰问题
因此,以下仅适用于Unity 2
- 您可以从Piotr Wlodek安装。然后,您需要使用以下方法启用它:
container.AddNewExtension<LazySupportExtension>();
对于任何使用MVC或Web API项目的用户,只需安装相关的Unity Bootstrapper Nuget软件包,即Unity.AspNet.WebApi用于Web API,Unity.MVC用于MVC
然后像平常一样注册类型,要么在代码中,要么通过配置文件。惰性实例将自动注入
private Lazy<IMapService> _mapService;
public HomeController(Lazy<IMapService> mapService)
{
//Lazy instance is injected automatically.
_mapService = mapService
}
private-Lazy\u-mapService;
公共HomeController(惰性映射服务)
{
//惰性实例是自动注入的。
_mapService=mapService
}
对于任何使用MVC或Web API项目的用户,只需安装相关的Unity Bootstrapper Nuget软件包,即Unity.AspNet.WebApi用于Web API,Unity.MVC用于MVC
然后像平常一样注册类型,要么在代码中,要么通过配置文件。惰性实例将自动注入
private Lazy<IMapService> _mapService;
public HomeController(Lazy<IMapService> mapService)
{
//Lazy instance is injected automatically.
_mapService = mapService
}
private-Lazy\u-mapService;
公共HomeController(惰性映射服务)
{
//惰性实例是自动注入的。
_mapService=mapService
}
“不走运”到底是什么意思?(例如,如果您得到了确切的错误消息)而且您似乎有不匹配的尖括号…是否需要添加ImportingConstructor
作为属性?“不走运”的确切含义是什么?(例如,如果您得到了确切的错误消息)而且您似乎有不匹配的尖括号…是否需要添加ImportingConstructor
作为属性?