c# - Autofac 6.2 不再(不再)允许使用私有构造函数的类?
问题描述
我有这段代码曾经在 Autofac 2.6 中工作,但现在不再在 6.2 (最新版本)中工作:
class Program
{
static void Main(string[] args)
{
Holder holder = null;
Build(c =>
{
holder = new Holder() { Verifiers = c.Resolve<Verifiers>() };
});
var res = holder.Verifiers;
Console.WriteLine("Success");
}
private static void Build(Action<IContainer> container)
{
var builder = new ContainerBuilder();
builder.RegisterAssemblyTypes(typeof(Verifiers).Assembly).AsSelf().AsImplementedInterfaces();
container(builder.Build());
}
}
public class PrivateConstructorClass
{
public static PrivateConstructorClass Create()
{
return new PrivateConstructorClass();
}
private PrivateConstructorClass() //this is the problem
{
}
}
public class Verifiers
{
}
public class Holder
{
public Verifiers Verifiers { get; set; }
}
由于此错误:
Autofac.Core.Activators.Reflection.NoConstructorsFoundException
HResult=0x80131500 消息=没有为“AutofacTest46PrivateConstructor.PrivateConstructorClass”类型找到可访问的构造函数。
Source=Autofac StackTrace:Autofac.Core.Activators.Reflection.DefaultConstructorFinder.GetDefaultPublicConstructors(Type type) at Autofac.Core.Activators.Reflection.DefaultConstructorFinder.FindConstructors(Type targetType) at Autofac.Core.Activators.Reflection.ReflectionActivator.ConfigurePipeline( IComponentRegistryServices componentRegistryServices, IResolvePipelineBuilder pipelineBuilder)
在 Autofac.Core.Registration.ComponentRegistration.BuildResolvePipeline(IComponentRegistryServices registryServices, IResolvePipelineBuilder pipelineBuilder) 在 Autofac.Core.Registration.ComponentRegistration.BuildResolvePipeline(IComponentRegistryServices registryServices) 在 Autofac.Core.Registration.ComponentRegistryBuilder.Build() 在 Autofac.ContainerBuilder.Build( ContainerBuildOptions 选项)在 AutofacTest46PrivateConstructor.Program.Build(Action`1 container) 在 D:.net Samples project\May 2021\AutofacTest46PrivateConstructor\Program.cs:line 30 at AutofacTest46PrivateConstructor.Program.Main(String[] args) in D:. net Samples project\May 2021\AutofacTest46PrivateConstructor\Program.cs:line 16
虽然我可以通过将构造函数类的修饰符从私有变为公共来“解决”这个问题,但我仍然有疑问:
- 这种行为是否记录在某处,即自从 Autofac 在以前允许的情况下不允许私有构造函数时?
- 我想排除只有非公共构造函数的类被 Autofac 注册,怎么做?
解决方案
自八年前 Autofac 2.6 发布以来,已经发生了很多事情。其中一件事是我们不考虑私有构造函数,正如您所注意到的。我确信它在某个发行说明中的某个地方,但是从那时起我们已经从 Google Code 转移到 GitHub,从 Subversion 转移到 Git,并且一些历史已经丢失。我可以看到至少从 2015 年开始就是这样。
解决方案是使用您自己的IConstructorFinder
实现。我们的默认版本在这里,因此您可以看到它的外观。然后,您可以使用FindConstructorsWith
扩展将您的构造函数查找器附加到您的类的注册中。
var finder = new MyCustomConstructorFinder();
var builder = new ContainerBuilder();
builder.RegisterType<MyType>().FindConstructorsWith(finder);
推荐阅读
- python - 如何比较 Dataframe 中的多值重复项
- android - 将适配器文本传递给片段创建问题
- c# - NavigationView 上的 Windows.UI.Xaml.Markup.XamlParseException
- database - 未指定关系类型的 Neo4j 查询
- python - Discord py - 带有字典变量的菜单
- java - 接口的默认方法存储在内存中的哪里?
- ios - iOS 中的黑莓集成
- python - 使用 tqdm 编码进度条
- bash - 添加在图像上突出显示日期的日历
- python - 不允许启动 AudioContext。必须恢复(或创建)