Service or Controller Sample Querying the DB

QueryService interacting with Persistence Layer using IUnitOfWork
Controller interacting  with Persistence layer in absence of Service Layer using IUnitOfWork
In case of Web App, IUnitOfWork is injected with Request Scope by DI/IOC container, because
unde the hood IUnitOfWork is dealing with Database Connections unmanaged resources.
In case of WPF/Window Applications the IUnitOfWork usually has Form Scope. When Form is disposed we also dispose the IUnitOfWork object. 
UnitOfWork ==> IUnitOfWork ==> DBContext

using System;
using System.Collections.Generic;
using System.Linq;
using CleanArchitecture.Application.Interfaces;

namespace CleanArchitecture.Application.Products.Queries.GetProductsList
{
    public class GetProductsListQuery 
        : IGetProductsListQuery
    {

       // IUnitOfWork
        private readonly IDatabaseService _database;

        public GetProductsListQuery(IDatabaseService database)
        {
            _database = database;
        }

// Sadly this sample does not use Entity Specific Repo. That is why 
Quering Logic has leaked into the Services/Controllers

        public List<ProductModel> Execute()
        {
            var products = _database.Products
                .Select(p => new ProductModel
                {
                    Id = p.Id,
                    Name = p.Name,
                    UnitPrice = p.Price
                });

            return products.ToList();
        }
    }
}

Comments

Popular posts from this blog

IGenricRepository

Summary of All Data Source Patterns