Onionizing Xamarin Part 3

For those who just want code: https://github.com/SuavePirate/Xamarin.Onion 

Don’t forget:

  1. Part 1 on the general project structure: Onionizing Xamarin Part 1
  2. Part 2 on our Domain and Application layers: Onionizing Xamarin Part 2

A strong and scale-able architecture is important in applications, especially in Mobile Apps. APIs and SDKs are constantly changing, new technology is constantly released, and team sizes are always changing. A solid Onion Architecture can save a development team a lot of time by making it simple to change service implementations, restrict access to certain areas, making logic flow easy to follow, and making testing isolated blocks of code easier.

Some of the important topics this will cover:

  • Separation of Concerns
  • Inversion of Control
  • Dependency Injection
  • Model-View-ViewModel
  • Testability
  • Why all these things are important

Part 3

In this section, we’ll start to dive into the code for our infrastructure layers (or at least what is important), including our business logic and data logic.

Let’s dive into the data layer.

Infrastructure.Data

This layer is our actual implementation of our Domain definitions, so we are going to implement things such as our Repositories, DataProviders, Stores, or anything else that interacts with our data directly.

From our previous post we defined our IGenericStore + IUserStore and our IGenericRepository + IUserRepository, so now let’s implement them.

GenericStore.cs and UserStore.cs

public class GenericStore<T> : IGenericStore<T>
{
    public List<T> Data { get; set; }
    public GenericStore()
    {
        Data = new List<T>();
    }
}

public class UserStore : GenericStore<User>, IUserStore
{
}

For the sake of just testing data, our store just contains a collection of data, however, this is where you could implement an observable collection, or more complex data types as well.

Now a look at the repositories – Our implementation of our repository is just going to use in-memory storage, but this is a place where you could implement SqlLite, Azure Mobile Tables, or local file storage instead. You could implement all of these easily and just switch out in your UserRepository which one it inherits! That’s one of the biggest bonuses of our Onion Architecture. The github repository demonstrates this well: https://github.com/SuavePirate/Xamarin.Onion/blob/master/src/OnionTemplate/OnionTemplate.Infrastructure.Data/Repositories/UserRepository.cs

GenericMemoryRepository.cs and UserRepository.cs

public class GenericMemoryRepository<T> : IGenericRepository<T>
{
    private readonly IStoreManager _storeManager;
    public GenericMemoryRepository(IStoreManager storeManager)
    {
        _storeManager = storeManager;
    }
    public void Add(T entity)
    {
        _storeManager.Set<T>().Data.Add(entity);
    }

    public void AddRange(IEnumerable<T> entities)
    {
        _storeManager.Set<T>().Data.AddRange(entities);
    }

    public Task CommitAsync()
    {
        return Task.FromResult(false); // we don't need to explicitly save changes
    }

    public Task<T> FindAsync(Func<T, bool> predicate)
    {
        var entity = _storeManager.Set<T>().Data.Where(predicate).FirstOrDefault();
    return Task.FromResult(entity);
    }

    public Task<IEnumerable<T>> GetAsync(Func<T, bool> predicate)
    {
        var entities = _storeManager.Set<T>()?.Data?.Where(predicate);
        return Task.FromResult(entities);
    }

    public void Remove(T entity)
    {
        _storeManager.Set<T>().Data.Remove(entity);
    }

    public void RemoveRange(T entities)
    {

    }
}

public class UserRepository : GenericMemoryRepository<User>, IUserRepository
{
    public UserRepository(IStoreManager manager)
    : base(manager)
    {
    }
}

That’s all we need to define for our data  layer for now. Next let’s look at our business logic layer and how it interacts with the data layer through references to our domain interfaces.

Infrastructure.Business

Our business layer is our implementation of our Application layer. So we are going to implement the IBaseService and IUserService we defined in the previous segment:

IBaseService.cs and IUserService.cs

public class BaseService : IBaseService
{
    public BaseService()
    {
    }

    public IEnumerable<string> Validate(object model)
    {
        if(model == null)
            return new List<string> { "Empty model received" };
        return null;
    }
}

public class UserService : BaseService, IUserService
{
    private readonly IUserRepository _userRepository;
    public UserService(IUserRepository userRepository)
    {
        _userRepository = userRepository;
    }
    public async Task<Result<UserTransferObject>> CreateUserAsync(NewUser model)
    {
        var errors = Validate(model);
        if (errors == null)
        {
            var entity = model.ToUser();
            _userRepository.Add(entity);
            await _userRepository.CommitAsync();

            return new Result<UserTransferObject>(new UserTransferObject(entity));
        }
        return new Result<UserTransferObject>(ResultType.Invalid, errors);
    }

    public async Task<Result<UserTransferObject>> FindByIdAsync(int userId)
    {
        var entity = await _userRepository.FindAsync(user => user.Id == userId);
        if (entity == null)
        {
            return new Result<UserTransferObject>(ResultType.Failed, "Could not find user with this Id");
        }
        return new Result<UserTransferObject>(new UserTransferObject(entity));
    }

    public async Task<Result<UserTransferObject>> RemoveByIdAsync(int userId)
    {
        var entity = await _userRepository.FindAsync(user => user?.Id == userId);
        if (entity == null)
        {
            return new Result<UserTransferObject>(ResultType.Failed, "Could not find user with this Id");
        }
        _userRepository.Remove(entity);
        await _userRepository.CommitAsync();
        return new Result<UserTransferObject>(new UserTransferObject(entity));
    }

    public async Task<Result<IEnumerable<UserTransferObject>>> GetValidUsers()
    {
        var entities = await _userRepository.GetAsync(user =>         !string.IsNullOrEmpty(user?.Email));
        return new Result<IEnumerable<UserTransferObject>>(entities?.Select(entity => new UserTransferObject(entity)));
    }
}

The biggest thing to point out is how the constructor for our UserService takes in an IUserRepository. Later we will set up our IoC container and inject our actual UserService so that the logic ties together. Doing this allows us to avoid referencing the Infrastructure.Data layer in our Infrastructure.Business layer which gives us full Separation of Concerns in our layers.

What’s Next

In the next segment, we’ll talk about implementing our Xamarin.Forms application, setting up our Inversion of Control and Dependency Injection, and tying it all together.

We’ll also look at each of our different platforms and talk about how we can utilize them without using Xamarin.Forms.

Finally, in the last segment, we will talk about how to truly utilize the Onion Architecture to test, pull, and change important pieces of our application without having to touch anything else.

 

Check out Part 4 to look at the Client Layer

Advertisement

6 thoughts on “Onionizing Xamarin Part 3”

  1. Nice write up. Digesting your template and IoC in general. I have a question for you.
    In
    Infrastructure-Repositories-UserRepository
    you make a comment if switch storage provider, be sure to change the dependency in IocConfig.
    I do not see why there would be a change in registration for this based on this template design.
    From what I can see you would just change the reference class from GenericMemoryRepo to GenericSqlLiteRepo.

    Thanks

    Like

    1. I guess the comment is worded wrong. If you want to change the UserRepository, then you’re correct, you can change the inheritance. However, this isn’t the ideal way to substitute the IUserRepository. What you should do is create a new implementation using the new inheritance (say something like “UserSqliteRepository”), then switch that IUserRepository implementation in the IoC container. Does that make more sense?

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s