SimpleInjector:注册集合时无法在构造函数中注册泛型类型

问题描述 投票:0回答:1

我有一个Funcs列表,其中包含我需要注册到容器的类型及其参数:

var LogCreaters = new List<Func<ILogFormat, FolderLocation, ILogWriter>>
{
    (fmt,path)=> new NlogWriter(new NlogConfiguration(fmt,path.logging)),
    (fmt,path)=> new DisplayWriter(fmt)
}

这是我尝试注册集合的方式:

container.Collection.Register<ILogWriter>(LogCreaters);

其次:

foreach (var item in LogCreater)
{
    container.Collection.Append<ILogWriter>(
        () => item(LogFormat, FolderLocation), LifeSpan.Scoped);
}

但是container.Verify()引发以下异常:

配置无效。为Logger类型创建实例失败了NlogWriter类型的构造函数包含带有名称“ config”并键入NlogConfiguration,但不是NlogConfiguration注册。要解决NlogConfiguration,必须在容器中注册。

我猜测是NlogWriter类型已在容器中注册,但其构造函数参数未在该过程中注册。在当前情况下,我如何将LogCreators及其构造函数和构造函数参数中的类型注册到容器。

我最近问this有关如何注册集合的问题,回答了我的问题,但我想我无法正确解释我的当前情况,因此我将再次发布此详细信息。

TIA。

c# .net dependency-injection ioc-container simple-injector
1个回答
0
投票

在您使用的框架中,有一个RegisterMany()函数,您可以使用该函数注册多个依赖项,该依赖项实际上使用_container.Collection.Register(types);

您不使用它来注册功能,而是注册实际的类型。所以代替

var LogCreaters = new List<Func<ILogFormat, FolderLocation, ILogWriter>>
{
    (fmt,path)=> new NlogWriter(new NlogConfiguration(fmt,path.logging)),
    (fmt,path)=> new DisplayWriter(fmt)
}

使用此:

var LogCreaters = new []{ typeof(NLogWriter), typeof(DisplayWriter)}; 

这将解决您的问题。

全世界对您的项目所使用的内部框架一无所知,因此下一次在发布给全世界之前,请问您的上级!

欢呼!

© www.soinside.com 2019 - 2024. All rights reserved.