Xamarin Forms 使用 Unity 为视图模型构造函数注册客户服务

Xamarin Forms Registering Customer Services with Unity for View Model Constructors

我试图在导航到 ViewModel 时将服务注入到它。尽管我在 Brian Lagunas 的博客、示例代码等上查看了参考资料,但似乎有些地方不对。

在我的 App.cs

public class App : PrismApplication
{
    protected override void OnInitialized ()
    {
        NavigationService.NavigateAsync ("SignInPage", animated: false);
    }

    protected override void RegisterTypes ()
    {
        Container.RegisterTypeForNavigation<SignInPage>();
        Container.RegisterType<IUserAuthentication, UserAuthenticationService>();
    }

}

注意:IUserAuthentication 和 UserAuthenticationService 命名空间的 using 语句已经到位。

SignInPageViewModel.cs

private INavigationService _navigationService;
private IUserAuthentication _userAuthenticationService;

public SignInPageViewModel(INavigationService navigationService, IUserAuthentication userAuthenticationService)
{
    _navigationService = navigationService;
    _userAuthenticationService = userAuthenticationService;
}

Container.RegisterType 似乎不接受泛型。我在 Unity 中看到的所有示例似乎都支持它,但我收到以下错误。

The non-generic method 'IUnityContainer.RegisterType(Type, Type, string, LifetimeManager, params InjectionMember[])' cannot be used with type arguments

这是一个构建错误。

包裹信息

您需要使用 Microsoft.Practices.Unity;

RegisterType 的通用版本是一种扩展方法,位于 Microsoft.Practices.Unity 命名空间中。要使用它,要么显式调用它

Microsoft.Practices.Unity.UnityContainerExtensions.RegisterType<ISomething, SomeService>( Container );

或添加

using Microsoft.Practices.Unity;