在Xamarin.forms中是否支持setter注入?
我在引导程序中注入了一个服务,如下所示:
在一个ViewModel中,我希望像这样将一个实例注入到一个属性中:
我在引导程序中注入了一个服务,如下所示:
Container.RegisterType<ICommonService, CommonService>();
在一个ViewModel中,我希望像这样将一个实例注入到一个属性中:
[Dependency]
public ICommonService CommonService { get; set; }
但在运行时,属性CommonService总是为空。
我使用的属性是Microsoft.Practices.Unity.DependencyAttribute,而不是Xamarin.Forms.DependencyAttribute
如果我在构造函数中注入,它就可以工作。
public LandingPageViewModel(INavigationService navigationService, ICommonService commonService)
编辑:添加了代码片段
public class Bootstrapper : UnityBootstrapper
{
protected override Page CreateMainPage()
{
try
{
return Container.Resolve<Views.LandingPage>();
}
catch (Exception exception)
{
//TODO: intent to get exception info
throw;
}
}
protected override void RegisterTypes()
{
DependencyResolver.Instance.Initialize(Container);
this.RegisterViews();
this.RegisterServices();
this.RegisterSingleton();
}
private void RegisterViews()
{
Container.RegisterTypeForNavigation<LandingPage>();
Container.RegisterTypeForNavigation<Page1>();
}
private void RegisterServices()
{
Container.RegisterType<ICommonService, CommonService>();
}
private void RegisterSingleton()
{
}
}
public partial class App : Application
{
public App()
{
InitializeComponent();
var bootstrapper = new Bootstrapper();
bootstrapper.Run(this);
}
protected override void OnStart()
{
// Handle when your app starts
}
protected override void OnSleep()
{
// Handle when your app sleeps
}
protected override void OnResume()
{
// Handle when your app resumes
}
}