属性注入(二传手注射)Prism for Xamarin.Forms

时间:2016-06-16 07:58:33

标签: c# dependency-injection xamarin.forms unity-container prism

Xamarin.forms是否支持setter注入?

我在这个引导程序中注入了一个服务

Container.RegisterType<ICommonService, CommonService>();

在viewmodel中,我希望将一个实例注入到像这样的属性

[Dependency]
public ICommonService CommonService { get; set; }

但是在运行时,属性CommonService始终为null。

我使用的属性是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
    }
}

1 个答案:

答案 0 :(得分:0)

嗯,他们从 Prism 7.0 开始移除了 DependencyAttribute 注入功能,我认为我们应该手动注册它。 (您的代码片段应该可以工作)

看:https://brianlagunas.com/whats-new-in-prism-for-xamarin-forms-7-0/

BrianLagunas Prism 7.0 changes