为什么 Unity 找不到我的参数化构造函数?

Why does Unity not find my parameterized constructor?

我的小菜鸟Bootstrapper配置容器如下:

protected override void ConfigureContainer()
{
    base.ConfigureContainer();
    RegisterTypeIfMissing(typeof(IUserSettingsProvider), typeof(JsonUserSettingsProvider), true);
    RegisterTypeIfMissing(typeof(IAppState), typeof(AppState), true);
    Container.RegisterType<TripleDesEncryptionService>(new InjectionConstructor(App.CryptoKey));
    Container.RegisterType<BaseViewModel>(new InjectionConstructor(Container.Resolve<IAppState>()));
}

而我的 BaseViewModel 只有一个演员:

public abstract class BaseViewModel : BindableBase, INotifyPropertyChanged
{
    protected BaseViewModel(AppState appState)
    {
        AppState = appState;
    }
    ...
}

当我尝试 运行 项目时,引导程序在 RegisterType<BaseViewModel> 上失败并抛出以下异常。

System.InvalidOperationException: 'The type ApptEase.Client.Infrastructure.ViewModels.BaseViewModel does not have a constructor that takes the parameters (AppState).'

AppState在应用启动代码中创建并注册到容器:

protected override void OnStartup(StartupEventArgs e)
{
    base.OnStartup(e);
    var boot = new Bootstrapper();
    boot.Run();
    Container = boot.Container;
    _appState = new AppState();
    Container.RegisterInstance(typeof(AppState), _appState);
}

您的 BaseViewModel class 构造函数受到保护。这对 Unity 是不可见的。但无论如何,正如用户 3615 在评论中所写 -

You cannot resolve abstract class since instance cannot be created

所以我建议显式注册一个具体的实现实例并将其映射到该基类型。

Container.RegisterInstance(typeof(BaseViewModel), new MyConcreteViewModel());

但最终你想要的其实是一个接口类型的注册。这通过模拟解锁了可测试性。