![](/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.