簡體   English   中英

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

[英]Property Injection (setter injection) Prism for Xamarin.Forms

Xamarin.forms 中是否支持 setter 注入?

我在引導程序中注入了這樣的服務

Container.RegisterType<ICommonService, CommonService>();

在視圖模型中,我想將一個實例注入到這樣的屬性中

[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
    }
}

嗯,他們從 Prism 7.0 開始刪除了DependencyAttribute注入功能,我認為我們應該手動注冊它。 (您的代碼片段應該可以工作)

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

BrianLagunas Prism 7.0 變化

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM