属性注入(setter注入)Xamarin.Forms的Prism

3
在Xamarin.forms中是否支持setter注入?
我在引导程序中注入了一个服务,如下所示:
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
    }
}

构造函数注入优于属性注入,那么如果使用构造函数注入,为什么要改变这个呢? - Ric .Net
@Ric,每个单独的功能都有其自身的使用目的,关键是何时使用以及如何正确设计。这个链接可以帮助你:https://msdn.microsoft.com/en-us/library/ff649447.aspx,参考章节为“何时使用属性(Setter)注入”。谢谢。 - khoailang
你真的需要INavigationService导航服务吗? - PEO
我确定我理解了你的问题,NavigationService只是使用构造函数注入的一个例子,基本上我们可以在那里注入多个依赖项,这是有效的。我的问题是是否支持“属性注入”,如果不支持,那么我将切换到另一种替代方法。我查找了一下,看起来Xamarin.Forms不支持。谢谢。 - khoailang
我相信你做得正确,只是为了双重检查一下,你放置 Container.RegisterType 的函数是在 protected override void RegisterTypes() 中吗? - PEO
我正在使用Prism,我将“注册类型”部分放在引导程序中。我还编辑了我的问题以添加更多的代码片段,谢谢。 - khoailang
1个回答

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接