James
James

Reputation: 223

Prism Xamarin 6.2 IDependencyService in service

I'm using SQLite for via ISQLite interface which is implemented on the standard way via [assembly: Dependency(typeof(SQLite_iOS))] ...

but also I'm trying to implement data access model via the Repository pattern

My BaseRepository class looks like this

public abstract class BaseRepository<TEntity, TKey> : IRepository<TEntity, TKey> where TEntity : class, new()
{
    private readonly SQLiteAsyncConnection _connection;

    protected BaseRepository(ISQLite sqlite)
    {
        _connection = sqlite.GetAsyncConnection();

        _connection.CreateTableAsync<TEntity>().Wait();
    }

For each model I have an implementation of the BaseRepository class

public class SectorsRepository : BaseRepository<Sectors, int>, ISectorsRepository
{
    public SectorsRepository(ISQLite context)
        : base(context)
    {

    }
}

I'm now struggling how to register each Repository class. Obviously, this doesn't work as I don't have an instance of dependencyService;

protected override void RegisterTypes()
    {

        Container.RegisterType<ISectorsRepository, SectorsRepository>(new InjectionConstructor(dependencyService.Get<ISQLite>()));
}

Any idea?

thanks

Upvotes: 0

Views: 301

Answers (2)

user5420778
user5420778

Reputation:

You shouldn't be using DependencyService at all. It's not needed. You already have a true DI container. Use that instead. Even if you do use the DependencyService attribute in your platform projects, you don't need to resolve them by calling the DependencyService. Prism will automatically resolve them for you. You also shouldn't be manually injecting anything into your ctor, because your container will do this for you automatically as long as you have registered your services with the container.

Upvotes: 1

James
James

Reputation: 223

To answer myself. This piece of code made it to work. The only thing I don't like is manual instancing of DependencyService. Does anyone has more elegant solution?

thanks

protected override void RegisterTypes()
        {
            DependencyService ds = new DependencyService();
            Container.RegisterType<IUnitOfWork, UnitOfWork>(new InjectionConstructor(ds.Get<ISQLite>()));
....
}

Upvotes: 0

Related Questions