1
头图

Minimal API is the latest feature provided by .NET 6. Compared with the traditional http://ASP.NET Core Web API, it is more direct. You can write a REST API with a few lines of code. Without the ancestral Startup.cs and Controller, API development can be completed through simple code. In the second phase of the .NET challenge, the Minimal API in .NET 6 is used as the main line of learning to complete related cloud native applications. Some friends asked how to make good use of Minimal API and how to build a cloud-native solution for Minimal API. Let me tell you about it below.

Let's get to know the Minimal API again


Compared with the traditional Web API, the Minimal API cancels the Controller, and the organization of files is more like Node.js. In the past, to start a Web API, .NET is still relatively complex compared to JavaScript, Go, Rust, Python and other languages. Web frameworks of. The .NET team hopes to simplify the .NET web framework through the Minimal API, allowing developers to complete simple API construction in one file. The following is a basic Minimal API project.

MapGet is an extension method of the EndpointRouteBuilderExtensions class. You can see that after setting the routing rules, it will pass a delegate parameter, and the compiler will convert it to RequestDelegate, which replaces the work of the Controller. Then use the app.Run() method to run our Minimal API application.

Architecture .NET 6 Minimal API project

In traditional Web API, CRUD is developed for different functions through Controller, but if we are Minimal API, how should we organize it? And can we still use the Repository Pattern?

  1. goodbye controller

Suppose we want to build an API about course information, with basic course information (course type, course list) and course selection information (student selection, student selection information for each course), if from the traditional Web API, you need to add CourseController and BookController two Controller, through different Actions to correspond to related routes, but for Minimal API, if we involve a lot of routes, our Program.cs file will be too large, which is very difficult to manage. Then we split the function points, or re-simulate the Controller to divide it is still very good.

The picture above is a picture I drew. By dividing Course and Book into two Modules, both modules contain routing settings. At this time, we make an interface, because each Module needs to include the method of adding routes, so it is made into an interface IBaseModule, which can be used by different modules in the future.

How to add it into Program.cs ? Let's use an extension method of IEndpointRouteBuilder to classify route additions

 public static class ModuleExtensions
{
​
    public static void Routers(this IEndpointRouteBuilder builder)
    {
​
        CourseModule courseModule = new CourseModule();
        BookModule bookModule = new BookModule();
        courseModule.AddModuleRoutes(builder);
        bookModule.AddModuleRoutes(builder);
​
​
    }
}

A trick here is that we can find the Module inherited from IBaseModule through the following typeof and call the method of adding routes after it is instantiated.

 public static void Routers(this IEndpointRouteBuilder builder)
    {
​
        var modules = typeof(IBaseModule).Assembly
            .GetTypes()
            .Where(p => p.IsClass && p.IsAssignableTo(typeof(IBaseModule)))
            .Select(Activator.CreateInstance)
            .Cast<IBaseModule>();
​
        foreach(var module in modules)
        {
            module.AddModuleRoutes(builder);
        }
​
    }
  1. Can the Repostitory model continue?

It is no doubt can continue to use. With the Repository pattern, you don't need to care what ORM you are using. All processing with ORM is handled in the Repository layer, which reduces coupling and provides better testability. In Microsoft documentation, there is the following comparison

Using Repository Pattern in Minimal API is no different from traditional http://ASP.NET MVC as a whole, here is a screenshot of Minimal API I use Repository pattern architecture

Note that some people think the Repository pattern is a bit outdated and over-architectural, but I think it's still very necessary to better manage your projects.

  1. dependency injection

Dependency injection solves the problem of how applications are independent of how objects are created. This is useful when you need configurable unit testing of your application. Dependency injection helps you make changes to your application more easily as your application grows in size and complexity. There is a very useful dependency injection method in http://ASP.NET Core, which is also in Minimal API. Since we manage function modules, we can also target module functions during dependency injection. The following is my design for module dependency injection. Combined with the Repository mode and the adjustments made in ModuleExtension.cs mentioned above, I also abstracted the common dependency injection of data connection.

 public static class ModuleExtensions
{
​
    static readonly List<IBaseModule> moduleList = new List<IBaseModule>(); 
​
    private static IEnumerable<IBaseModule> GetModules()
    {
        
        var modules = typeof(IBaseModule).Assembly
            .GetTypes()
            .Where(p => p.IsClass && p.IsAssignableTo(typeof(IBaseModule)))
            .Select(Activator.CreateInstance)
            .Cast<IBaseModule>();
​
        return modules;
    }
​
    public static void Routers(this IEndpointRouteBuilder builder)
    {
​
        foreach(var module in moduleList)
        {
            module.AddModuleRoutes(builder);
        }
​
    }
​
    public static void AddIoC(this IServiceCollection services)
    {
​
        foreach(var module in GetModules())
        {
            module.AddModuleIoC(services);
            moduleList.Add(module);
        }
​
    }
​
    public static void AddGlobalConfig(this IServiceCollection services)
    {
        services.AddScoped<CourseDataContext>();
        services.AddScoped<IUnitOfWork, UnitOfWork>();
    }
​
}

Pay attention to some places, although on the Minimal API, our dependency injection has registered different Services to be called by RequestDelegate, but when passing as a parameter, it is valid to add the [FromServices] attribute tag, as follows

 app.MapGet("/Course/GetCourse" ,([FromServices] ICourseService courseService , int typeID)=> {
            
        return  courseService.GetCourseList(typeID);
    });

Minimal API or Web API

When developing an API in http://ASP.NET Core, you are 90% using http://ASP.NET Core MVC. And when you use http://ASP.NET Core MVC to architect Web API, you will find it a little complicated, you need to meet all the requirements of http://ASP.NET Core MVC. The Minimal API just solves these problems, especially for some developers who only do API or entry, they only need concise code to complete work similar to Node.js. Some people ask me will Minimal API replace traditional Web API? I can tell everyone it won't. Again, it is the right way to choose the method that meets the needs of the project.

summary

In the cloud-native era, Minimal API is another powerful tool of .NET. The Minimal API of .NET 6 needs to be used well. In fact, it still uses a lot of old knowledge. For example, the construction method of Module, I refer to the open source Carter , and the Repository mode has not changed. Of course, it is still the familiar syntax of C#, which is We often say "everything is inseparable from it". Minimal API is not intended to replace Web API, but more to give developers an option. As a supplement to the knowledge points of the .NET Learning Challenge, I hope to give you a deeper understanding of the skills of Minimal API in practical application scenarios. The sample code this time is also put on my GitHub. If you are interested, you can visit this link to get the complete code .

related resources

Learn the Minimal API


Long press to identify the QR code and follow Microsoft China MSDN


微软技术栈
423 声望996 粉丝

微软技术生态官方平台。予力众生,成就不凡!微软致力于用技术改变世界,助力企业实现数字化转型。