Autofac 6.2 不允许(不再)使用私有构造函数 class 吗?

Autofac 6.2 doesn't (no longer) allow class with private constructor?

我有这段代码曾经在 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 Message=No accessible constructors were found for the type 'AutofacTest46PrivateConstructor.PrivateConstructorClass'.
Source=Autofac StackTrace: at 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)
at Autofac.Core.Registration.ComponentRegistration.BuildResolvePipeline(IComponentRegistryServices registryServices, IResolvePipelineBuilder pipelineBuilder) at Autofac.Core.Registration.ComponentRegistration.BuildResolvePipeline(IComponentRegistryServices registryServices) at Autofac.Core.Registration.ComponentRegistryBuilder.Build() at Autofac.ContainerBuilder.Build(ContainerBuildOptions options) at AutofacTest46PrivateConstructor.Program.Build(Action`1 container) in 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

虽然我可以通过将构造函数的修饰符 class 从私有更改为 public 来“解决”这个问题,但我仍然有疑问:

  1. 是否在某处记录了这种行为,即从 Autofac 禁止私有构造函数而以前允许的时候开始?
  2. 我想排除只有非public构造函数的class被Autofac注册,怎么办?

自八年前发布 Autofac 2.6 以来,发生了很多事情。正如您所注意到的,其中一件事是我们不考虑私有构造函数。我确定它在某处的发行说明中,但我们已经从 Google Code 转移到 GitHub,从 Subversion 转移到 Git,并且一些历史已经丢失。我可以看到它是这样的 since at least 2015.

解决方案是使用您自己的 IConstructorFinder 实现。我们的 default version is here so you can see what that would look like. You can then use the FindConstructorsWith extension 会将您的构造函数查找器附加到您的 class.

的注册中
var finder = new MyCustomConstructorFinder();
var builder = new ContainerBuilder();
builder.RegisterType<MyType>().FindConstructorsWith(finder);