Code Monkey home page Code Monkey logo

xer.cqrs.querystack's Introduction

Build

Branch Status
Master Build status
Dev Build status

Table of contents

Overview

Simple CQRS library

This project composes of components for implementing the CQRS pattern (Query Handling). This library was built with simplicity, modularity and pluggability in mind.

Features

  • Send queries to registered query handler.
  • Multiple ways of registering handlers:
    • Simple handler registration (no IoC container).
    • IoC container registration - achieved by creating implementations of IContainerAdapter.
    • Attribute registration - achieved by marking methods with [QueryHandler] attributes.

Installation

You can simply clone this repository, build the source, reference the dll from the project, and code away!

Xer.Cqrs libraries are also available as Nuget packages: NuGet

To install Nuget packages:

  1. Open command prompt
  2. Go to project directory
  3. Add the packages to the project:
    dotnet add package Xer.Cqrs.QueryStack
  4. Restore the packages:
    dotnet restore

Getting Started

(Samples are in ASP.NET Core)

Sample Query And Query Handlers

// Example query.
public class QueryProductById : IQuery<Product>
{
    public int ProductId { get; }

    public QueryProductById(int productId) 
    {
        ProductId = productId;
    }
}

// Async query handler.
public class QueryProductByIdHandler : IQueryAsyncHandler<QueryProductById, Product>
{
    private readonly IProductReadSideRepository _productRepository;
    
    public QueryProductByIdHandler(IProductReadSideRepository productRepository)
    {
        _productRepository = productRepository;    
    }

    public Task<Product> HandleAsync(QueryProductById query, CancellationToken cancellationToken = default(CancellationToken))
    {
        return _productRepository.GetProductByIdAsync(query.ProductId);
    }
}

// Sync query handler.
public class SyncQueryProductByIdHandler : IQueryHandler<QueryProductById, Product>
{
    private readonly IProductReadSideRepository _productRepository;
    
    public QueryProductByIdHandler(IProductReadSideRepository productRepository)
    {
        _productRepository = productRepository;    
    }

    public Product Handle(QueryProductById query)
    {
        return _productRepository.GetProductById(query.ProductId);
    }
}

// Attributed query handler.
public class QueryProductByIdHandler
{
    private readonly IProductReadSideRepository _productRepository;
    
    public QueryProductByIdHandler(IProductReadSideRepository productRepository)
    {
        _productRepository = productRepository;    
    }
    
    [QueryHandler]
    public Product Handle(QueryProductById query)
    {
        return _productRepository.GetProductById(query.ProductId);
    }
}

Query Handler Registration

Before we can dispatch any queries, first, we need to register our query handlers. There are several ways to do this:

1. Simple Registration (No IoC container)

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{            
    ...
    // Read-side repository.
    services.AddSingleton<IProductReadSideRepository, InMemoryProductReadSideRepository>();

    // Register query dispatcher.
    services.AddSingleton<IQueryAsyncDispatcher>((serviceProvider) =>
    {
        // This object implements IQueryHandlerResolver.
        var registration = new QueryHandlerRegistration();
        registration.Register(() => new QueryProductByIdHandler(serviceProvider.GetRequiredService<IProductReadSideRepository>()));

        return new QueryDispatcher(registration);
    });
    ...
}

2. Container Registration

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{            
    ...
    // Read-side repository.
    services.AddSingleton<IProductReadSideRepository, InMemoryProductReadSideRepository>();
    
    // Register query handlers to the container.
    // Tip: You can use assembly scanners to scan for handlers.
    services.AddTransient<IQueryHandler<QueryProductById, Product>, SyncQueryProductByIdHandler>();

    // Register query dispatcher.
    services.AddSingleton<IQueryAsyncDispatcher>((serviceProvider) =>
        // The ContainerQueryHandlerResolver only resolves sync handlers. 
        // For async handlers, ContainerQueryAsyncHandlerResolver should be used.
        new QueryDispatcher(new ContainerQueryHandlerResolver(new AspNetCoreServiceProviderAdapter(serviceProvider)))
    );
    ...
}

// Container adapter.
class AspNetCoreServiceProviderAdapter : Xer.Cqrs.QueryStack.Resolvers.IContainerAdapter
{
    private readonly IServiceProvider _serviceProvider;

    public AspNetCoreServiceProviderAdapter(IServiceProvider serviceProvider)
    {
        _serviceProvider = serviceProvider;
    }

    public T Resolve<T>() where T : class
    {
        return _serviceProvider.GetService<T>();
    }
}

3. Attribute Registration

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{            
    ...
    // Read-side repository.
    services.AddSingleton<IProductReadSideRepository, InMemoryProductReadSideRepository>();

    // Register query handler resolver. This is resolved by QueryDispatcher.
    services.AddSingleton<IQueryAsyncDispatcher>((serviceProvider) =>
    {
        // This implements IQueryHandlerResolver.
        var attributeRegistration = new QueryHandlerAttributeRegistration();
        // Register all methods with [QueryHandler] attribute.
        attributeRegistration.Register(() => new QueryProductByIdHandler(serviceProvider.GetRequiredService<IProductReadSideRepository>()));

        return new QueryDispatcher(attributeRegistration);
    });
    ...
}

Query Dispatcher Usage

After setting up the query dispatcher in the IoC container, queries can now be dispatched by simply doing:

...
private readonly IQueryAsyncDispatcher _queryDispatcher;

public ProductsController(IQueryAsyncDispatcher queryDispatcher)
{
    _queryDispatcher = queryDispatcher;
}

[HttpGet("{productId}")]
public async Task<IActionResult> GetProduct(int productId)
{
    Product product = await _queryDispatcher.DispatchAsync<QueryProductById, Product>(new QueryProductById(productId));
    if(product != null)
    {
        return Ok(product);
    }

    return NotFound();
}
...

xer.cqrs.querystack's People

Contributors

joel-jeremy avatar mvput avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

mallickhruday

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.