Xamarin Forms dependency service don't work with generics?

I'm trying to get an instance of generic class in Xamarin.Forms. If I use the code below everything works fine:

Interface

namespace PrismNinjectApp1.Application.Interfaces
{
    public interface IUserService { }
}

Concrete class

[assembly: Dependency(typeof(PrismNinjectApp1.Application.DomainServices.UserService))]
namespace PrismNinjectApp1.Application.DomainServices
{
    public class UserService : IUserService
    {
        public UserService() { }
    }
}

View Model

namespace PrismNinjectApp1.ViewModels
{
    public class MainPageViewModel : BindableBase, INavigationAware
    {
        private readonly IUserService _userService;

        public MainPageViewModel()
        {
            _userService = DependencyService.Get<IUserService>();
        }
        //Implementation of INavigationAware interface (I'm using Prism)
    }
}

But if I try do the same with generics I can't get the object instance:

Interface

namespace PrismNinjectApp1.test
{
    public interface IMyInterface<T> where T : class { }
}

Concrete class

[assembly: Dependency(typeof(PrismNinjectApp1.test.MyInterface<>))]
namespace PrismNinjectApp1.test
{
    public class MyInterface<T> : IMyInterface<T> where T : class { }
}

View Model

namespace PrismNinjectApp1.ViewModels
{
    public class MainPageViewModel : BindableBase, INavigationAware
    {
        private readonly IMyInterface<Users> _myInterface;

        public MainPageViewModel()
        {
            _myInterface = DependencyService.Get<IMyInterface<Users>>(); //Gets NULL value
        }
        //Implementation of INavigationAware interface (I'm using Prism)
    }
}

Users class is a domain entity

public class Users
    {
        [PrimaryKey, AutoIncrement]
        public int Id { get; set; }
        [MaxLength(100)]
        public string Name { get; set; }
    }

Any idea how I can get this object instance?

I trying to do this because I want to use generics services and repositories with basic CRUD and search methods with this structure

  1. App (project droid and ios)
  2. Shared (portable project)
  3. Application (for external services - portable projec)
  4. Domain - (portable project)
  5. Data - (portable project)

Xamarin Forms version: 2.3.4.247

Answers

  • You can try return the service as usual, and use Function with Generic. That works for me

  • Hey Tiago! Have you found a solution or did you apply any workaround meanwhile?

  • DennyyDennyy Member ✭✭

    I guess we'll never know

  • NMackayNMackay GBInsider, University mod
    edited September 2018

    As a side note, you shouldn't be using the DependancyService approach with Prism anyway, you should be using the PlatformInitializer approach and just register your services.

    Certainly in Prism we using DryIoC and generics.

Sign In or Register to comment.