![](/img/trans.png)
[英]Why default constructor does not work when parameterized constructor added?
[英]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
只有一个ctor:
public abstract class BaseViewModel : BindableBase, INotifyPropertyChanged
{
protected BaseViewModel(AppState appState)
{
AppState = appState;
}
...
}
当我尝试运行该项目时,引导程序在RegisterType<BaseViewModel>
上失败,并引发以下异常。
System.InvalidOperationException:'类型ApptEase.Client.Infrastructure.ViewModels.BaseViewModel没有采用参数(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类构造函数受到保护。 这对Unity不可见。 但是无论如何,正如用户3615在评论中写道-
您无法解析抽象类,因为无法创建实例
因此,我建议显式注册一个具体的实现实例并将其映射到该基本类型。
Container.RegisterInstance(typeof(BaseViewModel), new MyConcreteViewModel());
但是最后,您实际上想要的是接口类型的注册。 通过模拟解锁可测试性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.