[英]Why does Unity not find my parameterized constructor?
My tiny, novice, Bootstrapper
configures the container as follows: 我很小的新手
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>()));
}
and my BaseViewModel
has only one ctor: 我的
BaseViewModel
只有一个ctor:
public abstract class BaseViewModel : BindableBase, INotifyPropertyChanged
{
protected BaseViewModel(AppState appState)
{
AppState = appState;
}
...
}
When I try and run the project, the bootstrapper fails on RegisterType<BaseViewModel>
and throws the following exception. 当我尝试运行该项目时,引导程序在
RegisterType<BaseViewModel>
上失败,并引发以下异常。
System.InvalidOperationException: 'The type ApptEase.Client.Infrastructure.ViewModels.BaseViewModel does not have a constructor that takes the parameters (AppState).'
System.InvalidOperationException:'类型ApptEase.Client.Infrastructure.ViewModels.BaseViewModel没有采用参数(AppState)的构造函数。
AppState
is created and registered with the container in the application startup code: 创建
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);
}
Your BaseViewModel class constructor is protected. 您的BaseViewModel类构造函数受到保护。 Which is not visible to Unity.
这对Unity不可见。 But anyway, as user 3615 wrote in comments -
但是无论如何,正如用户3615在评论中写道-
You cannot resolve abstract class since instance cannot be created
您无法解析抽象类,因为无法创建实例
So I would suggest explicitly registering a concrete implementation instance and mapping it to that base type. 因此,我建议显式注册一个具体的实现实例并将其映射到该基本类型。
Container.RegisterInstance(typeof(BaseViewModel), new MyConcreteViewModel());
But in the end what you want is actually an interface typed registration. 但是最后,您实际上想要的是接口类型的注册。 That unlocks testability via mocking.
通过模拟解锁可测试性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.