Does Xamarin Forms dependency service not work with Generics?

Asked

Viewed 82 times

2

I need to generate an instance of a generic class with Xamarim Forms using dependcy service (or a DI framework). With the code below I can generate an instance without problems:

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 you use the code below the value returned for the _myInterface variable is always null

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

It is possible to generate this instance of the dependency service object?

I am trying to make this implementation to use generic services and repositories.

Version of Xamarin Forms: 2.3.4.247

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.