【发布时间】:2018-01-16 20:39:32
【问题描述】:
在将 SimpleInjector 从版本 2.8.3 更新到 v3.0.1 后,当我尝试将连接字符串传递给构造函数时,它会返回错误。这在过去运行良好,但在更新后出现问题。错误:
发生“System.ArgumentException”类型的第一次机会异常 在 SimpleInjector.dll 中
附加信息:MwmJobUpdateNotifier 类型的构造函数 包含不能是字符串类型的参数“connectionString” 用于构造函数注入。
这里是 SimpleInjector 容器的配置位置:
public static Container Configure(Container container)
{
// Force assembly reference so Interfaces load correctly.
if (typeof(IJobRepository) != null)
container.RegisterAllInterfacesForClassesInAssemblyContaining<JobRepository>();
// Force assembly reference so Interfaces load correctly.
if (typeof(IGmcService) != null)
container.RegisterAllInterfacesForClassesInAssemblyContaining<GmcService>();
container.Options.AllowOverridingRegistrations = true;
container.Register<IMwmJobUpdateNotifier>(() => new MwmJobUpdateNotifier(container.GetInstance<IJobRepository>(),
ConfigurationManager.ConnectionStrings["Coordinate_DatabaseEntities"].ConnectionString));
container.Options.AllowOverridingRegistrations = false;
MWM.Service.DAL.Config.AGI.AGIIocConfig.Configure(container);
return container;
}
看起来不喜欢我将两个参数传递给构造函数的方式。
已编辑:异常是在我注册了所有接口的ContainerException 类中触发的:
public static Container RegisterAllInterfacesForClassesInAssemblyContaining<T>(this Container container, Lifestyle lifestyle = null) where T : class
{
var assembly = typeof(T).Assembly;
var registrations = assembly.GetExportedTypes()
.Where(type => type.IsClass &&
type.GetInterfaces()
.Except(type.GetInterfaces().SelectMany(x => x.GetInterfaces()))
.Except(type.BaseType.GetInterfaces())
.Any())
.Select(type => new
{
Services = type.GetInterfaces()
.Except(type.GetInterfaces().SelectMany(x => x.GetInterfaces()))
.Except(type.BaseType.GetInterfaces()),
Implementation = type
});
foreach (var registration in registrations)
{
foreach (var service in registration.Services)
{
if (registration.Implementation.IsGenericTypeDefinition)
{
if (lifestyle == null)
{
container.Register(service.GetGenericTypeDefinition(), registration.Implementation.GetGenericTypeDefinition());
}
else
{
container.Register(service.GetGenericTypeDefinition(), registration.Implementation.GetGenericTypeDefinition(), lifestyle);
}
}
else
{
if (lifestyle == null)
container.Register(service, registration.Implementation);
else
container.Register(service, registration.Implementation, lifestyle);
}
}
}
return container;
}
异常在倒数第二个container.Register(...)调用中被捕获。
【问题讨论】:
-
你在哪一行得到这个异常?
-
v2 也不支持此功能。难道是因为某种原因
MwmJobUpdateNotifier是自动连接的,而它以前不是自动连接的? -
我在“conatiner.Register(service, registration.Implementation);”中得到了异常。如果我将 nuget 包降级到 v2.8.3,我就不会再遇到异常了。我在 v3 的重大更改中看到,这个 SI 版本更严格github.com/simpleinjector/SimpleInjector/releases
-
有趣的是,在容器发现字符串构造函数参数之前,您不能再替换注册。我想一种解决方案是将要排除的类型列表传递给
RegisterAllInterfacesForClassesInAssemblyContaining。 -
请您包含完整的堆栈跟踪信息吗?
标签: c# dependency-injection simple-injector