GithubHelp home page GithubHelp logo

wwwk / dotnet-core-api-template Goto Github PK

View Code? Open in Web Editor NEW

This project forked from superwalnut/dotnet-core-api-template

0.0 0.0 0.0 245 KB

This is a project template for .Net Core 3.1 API, pre configured Autofac, Swagger, Serilog, AutoMapper, Newtonsoft.Json

License: MIT License

C# 100.00%

dotnet-core-api-template's Introduction

Project Template - .Net Core 3.1 API + Autofac + Swagger + Serilog + AutoMapper

This is a project template for .Net Core 3.1 API, pre-configured Autofac, Swagger, Serilog, AutoMapper, Newtonsoft.Json using dotnet new -i Superwalnut.NetCoreApiTemplate to install project as a template, And using dotnet new core-api-autofac-swagger-serilog to create a project with the template.

Read full article on Medium https://medium.com/@mrkevin.wang/create-a-dotnet-core-api-boilerplate-template-with-most-popular-open-source-libraries-62ca1ab874c8

Pre-request

Table of Contents


Features

This is a development project template, it is NOT production ready. It only kickstarting your project so that you don't need to build from scratch.

  1. pre-Configured Autofac 5.2.0 registrations setup.

  2. Ready Swagger 5.5.1 endpoint.

  3. pre-Configured Serilog 2.9.0 console sinks.

  4. pre-Configured AutoMapper 10.0.0.

  5. pre-Installed Newtonsoft.Json 12.0.3

  6. pre-Setup NUnit Tests

  7. pre-Setup AutoFixture with Moq

  8. pre-Setup FluentAssertions


Installation

$ dotnet new -i Superwalnut.NetCoreApiTemplate

You should see '.Net Core API Autofac+Swagger+Serilog' in your template list by dotnet new -l

Redis .net core Template Screenshot

  • Using dotnet new redis-dotnet-core -n <your-project-name> to create a project with your own project name using this template
$ dotnet new core-api-autofac-swagger-serilog -n NetCoreDemo -o NetCoreDemo

This creates a project in folder NetCoreDemo

NetCore Demo


Documentation

Pre-configured Autofac

ContainerBuilder() that you can populate IServiceCollection and register your autofac modules in Startup.cs. Taking ApiModule from the template as an example, you can also create modules for your Service Layer, Repository Layer, etc.

        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            ...
            builder.RegisterModule<ApiModule>();

            var container = builder.Build();
            return container.Resolve<IServiceProvider>();
        }

Serilog & Automapper are registered in the ApiModule,

    public class ApiModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterLogger();
            builder.AddAutoMapper(x=>x.AddProfile<ApiAutoMapperProfile>());
        }
    }

Pre-configured swagger endpoint

You can access via https://localhost:5001/swagger

        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            ...
            if (!Environment.IsProduction())
            {
                services.AddSwaggerGen(
                    c =>
                    {
                        c.SwaggerDoc("v1", new OpenApiInfo { Title = "Api Swagger", Version = "v1" });
                    });
            }
            ...
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            ...
            if (!Environment.IsProduction())
            {
                app.UseSwagger();

                app.UseSwaggerUI(c =>
                {
                    c.SwaggerEndpoint("./v1/swagger.json", "Api V1");
                });
            }
            ...
        }

Pre-configured Serilog

With console sinks in the appsettings.json

  "Serilog": {
    "Using": [ "Serilog.Sinks.Console" ],
    "MinimumLevel": "Information",
    "WriteTo": [
      {
        "Name": "Console"        
      }
    ]
  }

And Serilog configuration in the program.cs

        public static IWebHostBuilder CreateHostBuilder(string[] args)
        {
            return WebHost.CreateDefaultBuilder(args)
                ...
                .UseSerilog((hostingContext, loggerConfiguration) => loggerConfiguration
                    .MinimumLevel.Override("Microsoft", LogEventLevel.Warning)
                    .MinimumLevel.Override("System", LogEventLevel.Warning)
                    .ReadFrom.Configuration(hostingContext.Configuration)
                    .Enrich.FromLogContext());
        }  

And registered in ApiModule,

    public class ApiModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            builder.RegisterLogger();
            ...
        }
    }

Pre-configured AutoMapper

With created example profile,

    public class ApiAutoMapperProfile : Profile
    {
        public ApiAutoMapperProfile()
        {
            CreateMap<Foo, FooDto>();
            ...
        }
    }

And register the profile in ApiModule for AutoMapper,

    public class ApiModule : Module
    {
        protected override void Load(ContainerBuilder builder)
        {
            ...
            builder.AddAutoMapper(x=>x.AddProfile<ApiAutoMapperProfile>());
        }
    }

Usage of AutoMapper in Controller, inject into the constructor

        private readonly IMapper _mapper;

        public FooController(..., IMapper mapper)
        {
            ...
            _mapper = mapper;
        }

Consumed in the controller method,

    var dto = _mapper.Map<List<Foo>, List<FooDto>>(result);

Pre-configured Unit tests

Setup Fixture for your test

        protected IFixture Fixture { get; private set; }

        [SetUp]
        public void SetupBase()
        {
            Fixture = new Fixture().Customize(new AutoMoqCustomization());
            Fixture.Customize<BindingInfo>(c => c.OmitAutoProperties());
            Fixture.Behaviors.Add(new OmitOnRecursionBehavior());
        }

Using Fixture To create mocks

        [SetUp]
        public void Setup()
        {
            _loggerMock = Fixture.Freeze<Mock<ILogger>>();
            _mapperMock = Fixture.Freeze<Mock<IMapper>>();

            _dtos = new List<FooDto> { new FooDto { Id = new Guid("59a54f7c-f7ea-41dc-89a8-d34aef7c8932"), Name = "test1" } };
            _mapperMock.Setup(x => x.Map<List<Foo>, List<FooDto>>(It.IsAny<List<Foo>>())).Returns(_dtos);
        }

And create instances of targeting objects

        var target = Fixture.Create<FooController>();

Validate via FluentAssertions

    okObjectResult.Should().NotBeNull();

    okObjectResult.Value.Should().BeOfType<List<FooDto>>();

    okObjectResult.Value.As<List<FooDto>>().Should().BeSameAs(_dtos);

Support

Reach out to me at one of the following places!


License

License


dotnet-core-api-template's People

Contributors

superwalnut 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.