Xamarin Forms Dependency Service not working with generics?

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

Interface

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

      

Specific class

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

      

Show 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 to do the same with generics, I cannot get an instance of the object:

Interface

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

      

Specific class

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

      

Show 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 are a domain object

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 am trying to do this because I want to use generics and repositories with basic CRUD and search methods with this structure

  • Application (droid and ios project)
  • Shared (portable project)
  • Application (for external services - portable project)
  • Domain - (portable project)
  • Data - (portable project)

Xamarin Forms Version: 2.3.4.247

+3


source to share





All Articles