You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Autofac解析WPF应用中非公共构造函数的抽象类?

解决Autofac无法解析带protected构造函数的抽象基类问题

核心问题排查

首先确认你是否误将抽象基类ListItemViewModelBase注册到了Autofac容器。抽象类本身不能被实例化,如果注册了它,Autofac会尝试创建其实例,但它的构造函数是protected,自然会抛出NoConstructorsFoundException。

正确的注册方式

只需要注册具体的子类PasswordItemViewModel和CardItemViewModel,不要注册抽象基类:

// 正确示例
var builder = new ContainerBuilder();
builder.RegisterType<PasswordItemViewModel>().AsSelf();
builder.RegisterType<CardItemViewModel>().AsSelf();
// 错误示例:不要注册抽象基类
// builder.RegisterType<ListItemViewModelBase>().AsSelf();

子类调用基类protected构造的处理

只要你的子类(比如PasswordItemViewModel)拥有公共构造函数,并且通过该构造函数调用基类的protected构造,Autofac可以正常解析子类实例,不需要额外配置。比如:

public class PasswordItemViewModel : ListItemViewModelBase
{
    // 子类的公共构造函数
    public PasswordItemViewModel(IDependency service) : base(service)
    {
        // 子类逻辑
    }
}

Autofac只会处理子类的公共构造,基类的protected构造由子类自行调用,容器不会直接尝试实例化基类。

特殊场景:允许Autofac解析非公共构造的类型

如果你的子类构造函数是非公共的(不推荐,除非有特殊设计需求),可以通过FindConstructorsWith方法配置Autofac扫描非公共构造:

builder.RegisterType<PasswordItemViewModel>()
       .AsSelf()
       .FindConstructorsWith(type =>
           type.GetConstructors(System.Reflection.BindingFlags.Instance | 
                               System.Reflection.BindingFlags.Public | 
                               System.Reflection.BindingFlags.NonPublic));

注意:非公共构造通常是为了限制实例化逻辑,随意开放可能破坏封装设计,请谨慎使用。

内容的提问来源于stack exchange,提问作者user14626381

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 20:31:35