mercredi 25 mars 2020

Repository - Service Pattern Sharing Entity

Think of an application designed to implement following layers:

  1. MyProject.UI (Blazor App)
  2. MyProject.Services (referenced by 1)
  3. MyProject.Repositories (referenced by 2)

    • Number 3 accesses ORM / web services (depending on the context).
    • Services layer contains Models and BL that is used by layer 1 to present the data

Question: Should the models that live in the Services layer be shared with the repository layer as well, or does the Repository layer needs to have their own entities / models to return the data? Consider the following example.

public interface IInstanceRepository
{
    Task<IEnumerable<InstanceData>> GetAllInstancesAsync(); //IEnumerable<T> is the object in MyProject.Services layer
}

public class InstanceRepository : IInstanceRepository
{
    //IEnumerable<T> is the object in MyProject.Services layer
    public async Task<IEnumerable<InstanceData>> GetAllInstancesAsync() 
    {
        //doesn't matter what happens in this part.
        await Task.Run(() => await SomeExternalDependency.GetInstances("blah blah"));
        return new List<InstanceData>
        {
            MyProp = "yeah boiii"
        };
        //doesn't matter what happens in this part.
    }
}

///////////////////////////////////////////////////////////

public interface IInstanceService
{
    Task<IEnumerable<InstanceData>> GetAllInstancesAsync();
}

public class InstanceService : IInstanceService
{
    private readonly IInstanceRepository _instanceRepository;

    public InstanceService(IInstanceRepository instanceRepository)
    {
        _instanceRepository = instanceRepository;
    }

    public async Task<IEnumerable<InstanceData> GetAllInstancesAsync()
    {
        //call the repo and get the data
        var instances = _instanceRepository.GetAllInstancesAsync(); 

        //apply business logic to data then return it
        return instances;
    }
}

///////////////////////////////////////////////////////////

# Inject IInstanceService and IInstanceRepository -> UI action -> call the service.GetAllInstancesAsync() method

PATTERN

If this is the wrong approach, how should this be structured? Should the Repository layer not return the type of the entity but a Dictionary<,> or whatever type is suitable for the return type and do the mapping in the Services layer? My understanding was to do the mapping in the Repo then return it and apply the BL.

Aucun commentaire:

Enregistrer un commentaire