简体   繁体   中英

In Xamarin Forms UnityServiceLocator namespace not found (Unity Dependency Injection & IoC containers)

I am facing the problem while implementing the Unity Container (Unity Dependency Injection & IoC containers) for not able to find the namespace for "UnityServiceLocator" in Xamarin Form.

I am getting the error at var unityServiceLocator = new UnityServiceLocator(Container);

error CS0246: The type or namespace name 'UnityServiceLocator' could not be found (are you missing a using directive or an assembly reference?)

I am using the.Net Framework 2.1 using Visual Studio 2019.

Nu-get Package Install as:

Unity (5.11.7)

CommonServiceLocator(2.0.5)

Xamarin.Essentials(1.3.1)

Xamarin.Forms(4.7.0.1.1080)

using System; 
using TestXamarinMVVM.Services;
using TestXamarinMVVM.View;
using Unity;
using CommonServiceLocator;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;

namespace TestXamarinMVVM
{
    public partial class App : Application
    {
        public static UnityContainer Container { get; private set; }

        public App()
        {
            InitializeComponent();

            Container = new UnityContainer();
            Container.RegisterType<IProductService, ProductService>();

            **var unityServiceLocator = new UnityServiceLocator(Container);**
            ServiceLocator.SetLocatorProvider(() => unityServiceLocator);


            //MainPage = new PersonDispaly();
            MainPage = new ProductPage();
        }

        protected override void OnStart()
        {
        }

        protected override void OnSleep()
        {
        }

        protected override void OnResume()
        {
        }
    }
}

I do not know where I am doing the mistake. Please help me.

You need to add the following packages for unity.

  1. Unity
  2. CommonServiceLocator
  3. Unity.ServiceLocation

The most recent way of doing this is shown in this example below . You will notice that you did make a few errors:

    public App()
    {
        InitializeComponent();

        //Init UnityContainer
        UnityContainer unityContainer = new UnityContainer();
        unityContainer.RegisterType<IProductsService, ProductsService>();

        var unityServiceLocator = new UnityServiceLocator(unityContainer);
        ServiceLocator.SetLocatorProvider(() => unityServiceLocator);

        MainPage = new ProductsPage();
    }

But you also forgot to add the following using statements, which means you likely need to add more nuget packages:

using Unity.ServiceLocation;
using UnityIoCContainer.Interfaces;
using UnityIoCContainer.Services;
using UnityIoCContainer.Views;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM