如何在使用惰性类型时注入参数?

时间:2014-08-26 10:52:18

标签: c# unity-container lazy-evaluation

我有一个以ITranslationService为参数的翻译类。注册Lazy<Translation>类型时如何注入翻译服务?这是我到目前为止所做的,但没有运气。

public class Translation
{
    public Translation(ITranslationService translationService)
    {
        // code here
    }
}

container.RegisterType<ITranslationService, TranslationService>();
container.RegisterType<Lazy<Translation>>(new InjectionConstructor(typeof(ITranslationService)));

尝试解析Lazy<Translation>类型时出现错误消息:

  

lazily-initialized类型没有public,无参数   构造

3 个答案:

答案 0 :(得分:2)

首先,Unity 3 now supports解析Lazy<T>(请参阅新增内容部分),因此您无需执行任何特殊操作,只需注册ITranslationService即可并且您将能够解决Lazy<Translation>

因此以下仅适用于Unity 2。

  • 您可以从Piotr Wlodek安装this nuget extension。然后,您需要使用以下命令启用它:

    container.AddNewExtension<LazySupportExtension>();
    

    然后,您就可以解析Lazy<T>个对象:

    var lazy = container.Resolve<Lazy<Translation>>();
    

    在您致电Translation之前,不会构建实际的lazy.Value对象。

  • 如果既没有获得Unity3也没有获得该扩展,您仍然可以尝试手动配置Unity2并解析这些对象。

    在您的情况下,您需要使用接收Func<T>作为参数的constructors in Lazy<T>之一。 (这是一个函数,没有参数返回T的实例,或者在你的情况下返回Translation)。

    在Unity中注册InjectionFactory时可以使用Lazy<Translation>,这是一种构造Lazy<Translation>对象的工厂方法。惰性对象将在其构造函数中接收一个初始化函数,该函数使用Unity来解析Translation

    container.RegisterType<Lazy<Translation>>(
     new InjectionFactory(c => new Lazy<Translation>(() => c.Resolve<Translation>()) ));
    

答案 1 :(得分:1)

Unity支持Lazy<T>,但您必须对其进行配置:

unityContainer.AddNewExtension<LazySupportExtension>();
然后不要

container.RegisterType<Lazy<Translation>(new InjectionConstructor(typeof(ITranslationService)));

但改为:

container.RegisterType<Translation>();

使用如下:

unityContainer.Resolve<Lazy<Translation>>();

答案 2 :(得分:0)

对于使用MVC或Web API项目的任何人,只需安装相关的Unity Bootstrapper Nuget软件包,即用于Web API的Unity.AspNet.WebApi和用于MVC的Unity.Mvc。

然后像往常一样注册您的类型,无论是在代码中还是通过配置文件。 Lazy实例将自动注入

private Lazy<IMapService> _mapService;

public HomeController(Lazy<IMapService> mapService)
{
    //Lazy instance is injected automatically.
    _mapService = mapService

}