Coder Social home page Coder Social logo

ajays1991 / genericcontroller Goto Github PK

View Code? Open in Web Editor NEW
0.0 0.0 0.0 5.67 MB

In REST api there are common CRUD service interface for every model served by controller for each model. In most of the scenarios the code for implementing Create, Get, Index, Delete, Update for each model is same and writing the same code again in all the controllers can be avoided by implementing generics for the controllers. In this article i have also implemented generic implementation for the repository pattern for entity framework. It reduces the amount of code we need to implement REST service

License: MIT License

C# 95.12% Dockerfile 4.88%

genericcontroller's Introduction

Generic Controller ApplicationFeatureProvider

Note

We will make an effort to support the library, but we reserve the right to make incompatible changes when necessary.

Current Version is 1.0.1 Target Framework netcoreapp3.1

Installation

You can install the package from package manager console by running the following command in the package manager console

PM> Install-Package GenericRestController -Version 1.0.1

OR

Click Manage Nuget Packages on the project dependencies and search GenericRestController

This package is registered with IServiceCollection and injected into container using Microsoft.Extensions.DependencyInjection

Basic working information

This package takes in Dictionary class where each ModelType is mapped to its corresponding Request and Response models

Create an static EntityTypes class in your project with method model_types which returns Dictionary<TypeInfo, Type[]>. I am showing an example where i have two database entities name Album and Artist and where each model type points to its own Request and Response Types.

using System;
using System.Collections.Generic;
using System.Reflection;
using Data.entities;
using TestGenericController.Entities;

namespace TestGenericController.ControllerFactory
{
    public static class EntityTypes
    {
        public static Dictionary<TypeInfo, Type[]> model_types()
        {
            return new Dictionary<TypeInfo, Type[]>()
            {
                { typeof(Albums).GetTypeInfo(), new Type[] { typeof(Albums).GetTypeInfo() ,typeof(AlbumRequest).GetTypeInfo(), typeof(AlbumResponse).GetTypeInfo() } },
                { typeof(Artists).GetTypeInfo(), new Type[] { typeof(Artists).GetTypeInfo() ,typeof(ArtistRequest).GetTypeInfo(), typeof(ArtistResponse).GetTypeInfo() } }
            };
        }
    }
}

Now we will add GenericController service container in the ConfigureService method and pass our entity types static dictionary and opentype restcontroller implemented. This will create controllers for all our models i.e it will add AlbumsController and ArtistsController.

 public void ConfigureServices(IServiceCollection services)
{
    services.AddGenericController(TestGenericController.ControllerFactory.EntityTypes.model_types(), typeof(RestController<,,>));
}

You can modify the Opentype generic controller to pass even more entity specific types i.e if you are using mediator pattern to talk between persistence layer and controllers then you can edit your type dictionary to have RequestHandlers for Ablumn model like TEntityHandler which can reslove to AlbumEntityHandler.

RestController Implementation.

Now we implement RestController(open type generic controller) which implement IGenericController from GenericController.Controller.Interface. Here i am sharing my example where i am implementing my create, get method and on run time T, TRequest, TResponse will be resolved to proper types, like if you hit api/albums url T will be Albums, TRequest will be AlbumsRequest, TResponse will be AlbumsResponse.

I have used automapper for transation and Generic Rep You can use/contruct/implement any datacontext strategy and your own authentication and authorization strategies and decorators.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using GenericController.Controller.Interface;
using AutoMapper;

using Data.Repositories;

namespace TestGenericController.Controllers
{
    public class RestController<T, TRequest, TResponse> : IGenericController<T, TRequest, TResponse> where T : class where TRequest : class where TResponse : class
    {
        private IGenericRepository<T> Repository { get; set; }

        private IMapper Mapper { get; set; }

        public RestController(IGenericRepository<T> _repository, IMapper _mapper)
        {
            Repository = _repository;
            Mapper = _mapper;
        }

        public async Task<TResponse> Get(int key)
        {
            var result = await Repository.Get(key);
            return Mapper.Map<T, TResponse>(result);
        }

        public async Task<TResponse> Create(TRequest request)
        {
            T db_model = Mapper.Map<TRequest, T>(request);
            var result = await Repository.Add(db_model);
            return Mapper.Map<T, TResponse>(result);
        }
        
    }
}

This Repository have a project TestGenericController for fully working solution using this Package.

To Do

Make GenericController to offer a SearchManager interface to build queries by plugging in any configurable adapter for MSSQL, CosmosDB, Elasticsearch Or MongoDB

Support

Please report bugs at the project on Github. Please don't hesistate to ask questions as issues in the repository. I am open to hear suggestions to improve this furthur and in version 2.0.0 version i am planning to rollout my first Todo.

genericcontroller's People

Contributors

ajays1991 avatar

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.