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

本文关键字:类型 注入 参数 | 更新日期: 2023-09-27 18:19:23

我有一个Translation类,它将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>类型时的错误消息:

惰性初始化类型没有公共的无参数类型构造函数

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

首先,Unity 3现在支持解决Lazy<T>(见什么是新的部分),所以你不需要做任何特别的,只是注册ITranslationService,你将能够解决Lazy<Translation>

所以以下内容只适用于Unity 2。

  • 你可以从Piotr Wlodek安装这个nuget扩展。然后您需要使用:

    来启用它
    container.AddNewExtension<LazySupportExtension>();
    

    您将能够解析Lazy<T>对象:

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

    并且实际的Translation对象在调用lazy.Value之前不会被构造。

  • 如果既没有得到Unity3也没有扩展是一个选项,你仍然可以尝试手动配置Unity2和解析这些对象。

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

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

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

Unity支持Lazy<T>,但你必须配置它:

unityContainer.AddNewExtension<LazySupportExtension>();

then don't do

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

而是:

container.RegisterType<Translation>();

并按如下方式使用:

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

对于任何使用MVC或Web API项目的人,只需安装相关的Unity Bootstrapper Nuget包,即Unity. asp.net . webapi和Unity。Mvc for Mvc。

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

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