Open Closed

Vertical Slice (Bounded Context Module) Should it own the user interface also? #3747


User avatar
0
cangunaydin created

Hello, I have come up to interesting video on youtube from Mauro Servienti. In his presentation he was explaining, about different bounded contexts responsible for different parts of the application. But he used view model composition and decomposition while building the user interface. This makes the solution interesting. Interesting part was each different module wasn't owning the user interface since view was composed from different bounded contexts of the application. https://www.youtube.com/watch?v=KkzvQSuYd5I

So in abp, mostly when you create a bounded context, I automatically think that view should also belong to that module (bounded context). Let me give you an example I was playing around.

I have Product Aggregate which consists of

Product: Aggregate Root

Id: Guid Name: string Description:string StockQuantity:int Price: decimal

also i have Order aggregate which consists of

Order: Aggregate Root

Id:Guid Name: string Items: List<OrderItem> TotalValue:decimal

OrderItem : Entity

Id:Guid OrderId:Guid ProductId:Guid Price: decimal Quantity: decimal Subtotal: decimal

So i wanted to seperate this to two bounded contexts Which is "inventory bounded context" and "sales bounded context". I know that Product in "Sales Bounded Context" and "Inventory Bounded Context" are not the same. In "Sales Bounded Context" i am not interested in how many items are in the stock.

So here the problem arises when i want to create the user interface in "Sales Bounded Context" to create an order. Since I do not know anything about Product, how am i going to list the products here? Two solutions i can think of.

Whenever product is created or updated or deleted on "Inventory bounded context" I will handle that event and create aggregate on "Sales bounded context". So i will copy the product information needed to my "Sales bounded context". Then i can use that in "Sales bounded context".

Second solution is to use IProductAppService in presentation layer of "Sales Bounded Context" which will list the products. This means i need to give the reference to HttpApi.Client project of "Inventory Bounded Context" module. (I don't know what kind of problems does this make? am i coupling my code to the other bounded context?)

Mauro Servienti in the video is giving another solution which says that, presentation layer should be another project which will compose and decompose those bounded contexts which is "inventory bounded context" and "sales bounded context"

So i am pretty confused which way is gonna be the right way. Before I watched the video i was more leaning into copying the products on the "sales bounded context" since it has different properties in that context. Do you have any suggestions how to move forward in these cases? Any advice will be much appreciated. Thank you for reading it.


12 Answer(s)
  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    Hi,

    ABP has an eshop microservice example, you can take a look:

    https://github.com/abpframework/eShopOnAbp

  • User Avatar
    0
    cangunaydin created

    Hello @liangshiwei As i understand (pls correct me if i am wrong), In microservice solution you don't use the user interface(or web layer) for microservices instead one web app that will unify whole views. And this web app(in EshopOnAbp,it is PublicWebApp) do the requests through gateway (WebPublicGateWay) by using reverse proxy.

    So here is the question my project will stay monolith for a while and according to changes it might evolve to microservices in the future, while my modules are monolith where should i implement the user interface to create an order, and if this is going to be inside the module, what should i do to list the products?

    Thank you for your patience and for your help a lot.

  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    As i understand (pls correct me if i am wrong), In microservice solution you don't use the user interface(or web layer) for microservices instead one web app that will unify whole views

    It's up to you, ABP also supports creating modules without UI: https://docs.abp.io/en/commercial/latest/startup-templates/module/creating-a-new-solution#without-user-interface

    Of course, the UI layer should be one web app, actually PublicWebApp is it, It just references the UI class library of other modules.

    So here is the question my project will stay monolith for a while and according to changes it might evolve to microservices in the future, while my modules are monolith

    No actually, you can create a Product module, Order module, etc...

    See: https://docs.abp.io/en/abp/latest/Microservice-Architecture#microservice-for-new-applications

    ABP provides Identity, Saas, Permission ... modules, they are completely separate solutions, but we can make them part of a monolithic application(app pro template) or as independently deployed services(microservice template)

  • User Avatar
    0
    cangunaydin created

    Of course, the UI layer should be one web app, actually PublicWebApp is it, It just references the UI class library of other modules.

    as i understand all the microservice modules do not have any presentation layer which means EshopOnAbp.PublicWeb project do not depend on any microservice module presentation layer (cause there is none, which is not needed on microservice modules in this case). It implements the necessary user interface inside that project. For ex:

      public class ProductDetailModel : AbpPageModel
        {
            [BindProperty(SupportsGet = true)]
            public int OrderNo { get; set; }
    
            public ProductDto Product { get; private set; }
            public bool IsPurschased { get; private set; }
    
            private readonly IPublicProductAppService _productAppService;
            private readonly IOrderAppService _orderAppService;
    
            public ProductDetailModel(
                IPublicProductAppService productAppService,
                IOrderAppService orderAppService)
            {
                _productAppService = productAppService;
                _orderAppService = orderAppService;
            }
    
            public async Task OnGet(Guid id)
            {
                IsPurschased = (await _orderAppService.GetMyOrdersAsync(new GetMyOrdersInput())).Any(p => p.Items.Any(p => p.ProductId == id));
                Product = await _productAppService.GetAsync(id);
            }
        }
    

    this is a sample from EshopOnAbp, it is ProductDetail page as you can see it is dependent on OrderAppService and ProductAppService while creating the ui. You can do this if you implement the presentation layer out of your modules, like in the demo project EshopOnAbp.

    I will try to ask the question from another perspective. If I need to convert the EshopOnAbp project to monolith app, in where should i create the user interface for ProductDetail page?

    Cause product belongs to Catalog Module and Order belongs to ordering module. Or you shouldn't implement the ProductDetail page in any modules presentation layer and keep it in your main app?

  • User Avatar
    0
    liangshiwei created
    Support Team Fullstack Developer

    EshopOnAbp.PublicWeb project do not depend on any microservice module presentation layer

    Sorry, the EShopOnAbp uses angular as the backend UI.

    If you create a microservice template, you will see it.

    I will try to ask the question from another perspective. If I need to convert the EshopOnAbp project to monolith app, in where should i create the user interface for ProductDetail page?

    As I said, the module's web project is just a Razor Libary, Its purpose is to create a reusable UI library, you can write all UI codes in one Web application or split into multiple UI libraries and use it in the Web application.

    About Razor library: https://learn.microsoft.com/en-us/aspnet/core/razor-pages/ui-class?view=aspnetcore-6.0&tabs=visual-studio

  • User Avatar
    0
    cangunaydin created

    Hello again, I think we couldn't understand each other :) I know that i can create razor pages. My question is out of scope of what kind of user interface tech. you use.

    just let me try another way to explain myself.

    Let's think about 3 different bounded contexts.

    1- Sales 2- Marketing 3- Shipping

    All of them has product properties related to product.

    So let's say.

    Marketing

     public class Product
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public string Description { get; set; }
        }
    

    Sales

     public class ProductPrice
        {
            public int ProductId { get; set; }
    
            public decimal Price { get; set; }
        }
    

    Shipping

     public class ProductShippingOptions
        {
            public int Id { get; set; }
            public int ProductId { get; set; }
            public List<ShippingOption> Options { get; set; } = new List<ShippingOption>();
        }
    
        public class ShippingOption
        {
            public int Id { get; set; }
            public int ProductShippingOptionsId { get; set; }
            public string Option { get; set; }
            public int EstimatedMinDeliveryDays { get; set; }
            public int EstimatedMaxDeliveryDays { get; set; }
        }
    

    so each bounded context is responsible for product details that they care.

    So let's think about a moment I am listing products on my web app (it doesn't matter which tech i use). The user wants to see name price and shipping options of the product on a listed view.

    If my web app is Monolith App, How should i compose those 3 different services together in a list? If my web app is Microservice, How should i compose those 3 different services together in a list?

    3 bounded contexts are different modules and they don't know about each other.

    As i see on EshopOnAbp, most of the data is copied between bounded contexts.
    here is the code from EshopOnAbp. This is the OrderItem from Ordering Bounded Context.

    public class OrderItem : Entity<Guid>
    {
        public string ProductCode { get; private set; }
        public string ProductName { get; private set; }
        public string PictureUrl { get; private set; }
        public decimal UnitPrice { get; private set; }
        public decimal Discount { get; private set; }
        public int Units { get; private set; }
        public Guid ProductId { get; private set; }
    

    here is the product from Catalog Bounded Context

     public class Product : AuditedAggregateRoot<Guid>
        {
            /// <summary>
            /// A unique value for this product.
            /// ProductManager ensures the uniqueness of it.
            /// It can not be changed after creation of the product.
            /// </summary>
            [NotNull]
            public string Code { get; private set; }
    
            [NotNull]
            public string Name { get; private set; }
    
            public float Price { get; private set; }
    
            public int StockCount { get; private set; }
    
            public string ImageName { get; private set; }
            
    

    And in Basket Bounded Context. the app calls the Catalog Bounded Context to get the Product info and caching it.(through _productPublicGrpcClient). This is some kind of composition in microservice level but isn't this should be composed in the gateway instead of Basket Service?

    public class BasketItemDto
    {
        public Guid ProductId { get; set; }
        public string ProductName { get; set; }
        public string ProductCode { get; set; }
        public string ImageName { get; set; }
        public int Count { get; set; }
        public float TotalPrice { get; set; }
    }
    

    is there any other way like viewmodel composition and decomposition that I can use so we don't need to copy the staff around for microservices and i am curious how this composition can happen if i decided to use my modules as monolith?

  • User Avatar
    0
    gterdem created
    Senior .NET Developer

    Basically, there are 2 ways to for UI development in a microservice template: - Modular UI development: Add the UI pages in the microservice itself by referencing the HttpApi.Client and Web layers by the end application. We use this sample in the eShopOnAbp back-office application (angular) - Monolith UI development: Develop the UI inside the end-running application by referencing the HttpApi.Client layer. We use this sample in the eShopOnAbp public-web application (mvc/razor).

    More info at microservice UI development docs.

    But I assume you are not asking this exactly. If I understand correctly, you ask for a way of providing report-like data for the UI that combines data from multiple microservices. (Correct me if I am wrong)

    In that case, you can use the gateway aggregator pattern to achieve that. There are some gateways that can already handle this (even with UI like KrakenD). The microservice template uses ocelot and ocelot has also request aggregation that you can use. Although, the gateways are running applications. You can manually write your aggregator or manual code to call for different microservices and return for a manual request.

    We don't have an example for that yet and it is not automatically supported since we use proxying directly based on the end-points. You need to write custom end-points for both the application and the request handler (gateway).

    But we plan to handle this scenario in the eShopOnAbp sample once we decided how to do it.

  • User Avatar
    0
    cangunaydin created

    Hello Galip, Thanks for the answer. I have checked out the "gateway aggregator pattern". And yes this is the thing that i am looking for at the first sight. But there is always but... :) aggregator pattern solves some of my problems for the above example i give. For ex:

    If i want to get the details of the product with the id 1. yes aggregator pattern most likely solves my problem. But what about list with search? and what about if i am going to do paging and sorting? and what about multiple column sorting? those are kind of difficult scenarios since data has been shared on different bounded contexts. (pictures are from ViewModel Composition Series of Mauro Servienti, https://milestone.topics.it/2019/02/28/into-the-darkness-of-viewmodel-lists-composition.html)

    Also another problem is Decomposition. What i mean by that is when i want to create product from scratch from the nice user interface with all the properties in one page and hit the save button. I need to send every piece of data to the related bounded context. Sth like this. (picture is from the video that i shared, from a ddd conference)

    so to manage the things that i have mentioned over here, they have implemented a kind of asp.net core route interceptor which gets the request and calling the parties that is participated in that route, so for ex.

    if i do a Get Request on the gateway, sth like api/product/1

    then the interceptor will catch this request and look at the contributors (with mediatr pattern) that is registered for this route and call their handle() methods so dto (or viewmodel) can be composed from each contributors.

    similarly if i do a Post Request on the gateway, sth like api/product/

    then the interceptor will catch this request and look at the contributors (with mediatr pattern) that is registered for this route and call their handle() method but sth is little different this time since you need a transactional boundary they use message broker to do the operation instead of http request.

    In conclusion my point is, i have decided to use this concept on abp project, but i am not sure what i am going to gain or loose, so i need to implement and see if it works at the end. So if you have any ideas how this can be done inside abp or any advices about which way should i go, i would like to hear it very much. Thanks for your time and reading it anyway.

  • User Avatar
    0
    gterdem created
    Senior .NET Developer

    Hello,

    Ok, the aggregator pattern solves the problem of how to fulfill the complex data requirements of your UI from multiple services. There are other solutions to this problem, but this is what comes to my mind first and I think it is very feasible and effective.

    Your second question is about searching. What happens when we need to search with different parameters that need to be searched in different microservices? My personal opinion, there should be a different microservice that solely should be responsible for searching. Instead of making a request to N different microservices, I would create a new microservice that gets fed by other microservices. It can be achieved by using events, background jobs.

    We are planning to implement these kinds of complexities into the eShopOnAbp solution but we are also investigating and brain-storming. Since there are lots of ways to solve a problem in distributes systems. The important part is comparing the advantages and disadvantages.

    I would also suggest checking out Jimmy Bogard's Avoid Microservice Megadisasters presentation. If I remember correctly, he is sharing some solutions for some of the complex problems.

  • User Avatar
    0
    cangunaydin created

    Hello again, Thanks for the link, i have watched it now and totally agree on some parts. Also i think if your search needs to be complex you definitely need another microservice for that. But also i have some parts that i disagree.

    But before that i am curious about your opinion, how to do the save operations? How you should do that in a microservice architecture if you need to have multiple requests. You can design your pages according to a call that you are gonna do. but that is a kind of limitation from a ui perspective.(Ex: First update name and description, then user will switch to another modal or page to update the price and so on).

    The parts that i disagree on the video is, if you hold all the information in a seperate db from different services( i am not saying this is not the way,in some cases you should, for ex,if you wanna do search, paging and sorting together). Basically what you do is kind of cache, and what i believe is in most of the cases, you can do the cache in the gateway instead of another service. And if you do on the gateway level you can give different cache timeout values.

    What i mean by that is if marketing is holding the information about name,description. and Sales holding the information about the price. Price information can be cached per day but marketing can be cached for a week so you don't need to call each microservice whenever requests comes(or you can get that information directly from db or text document).

    I also started to implement a kind of viewmodel composition gateway on a scratch abp template. I have a question about where the conventional endpoint routes are configured. I want to create an extra endpoint middleware that will intercept the call coming to the gateway and dispatch it to multiple methods and compose the returning values. I have tried to look at the source code but couldn't find where you invoke the method info for the application service endpoints. Can you direct me to the necessary part?

    I think in AbpServiceConvention all the services and controllers are converted to endpoints, but i couldn't connect the dots, where and how this class have been used. https://github.com/abpframework/abp/blob/dev/framework/src/Volo.Abp.AspNetCore.Mvc/Volo/Abp/AspNetCore/Mvc/Conventions/AbpServiceConvention.cs#L22

    Thanks for reading and your input.

  • User Avatar
    0
    gterdem created
    Senior .NET Developer

    Sorry for the late response,

    How you should do that in a microservice architecture if you need to have multiple requests. You can design your pages according to a call that you are gonna do. but that is a kind of limitation from a ui perspective.(Ex: First update name and description, then user will switch to another modal or page to update the price and so on).

    This is highly debatable and based on the application business itself. You can design it as a single request posting data to multiple microservices using the aggregate pattern. It should work fine. If the UX designers (or decision makers) request multiple requests for better UX than you can do so. It is all about advantages and disadvantages.

    The parts that i disagree on the video is, if you hold all the information in a seperate db from different services( i am not saying this is not the way,in some cases you should, for ex,if you wanna do search, paging and sorting together). Basically what you do is kind of cache, and what i believe is in most of the cases, you can do the cache in the gateway instead of another service. And if you do on the gateway level you can give different cache timeout values.

    It is not caching, it is data duplication. You can also apply caching on it.

    What i mean by that is if marketing is holding the information about name,description. and Sales holding the information about the price. Price information can be cached per day but marketing can be cached for a week so you don't need to call each microservice whenever requests comes(or you can get that information directly from db or text document).

    As I have mentioned above, it is not caching but data duplication. You can handle data changes by events. It is also reasonable to apply caching on this microservice as well that uses events to invalidate cache.

    I also started to implement a kind of viewmodel composition gateway on a scratch abp template. I have a question about where the conventional endpoint routes are configured. I want to create an extra endpoint middleware that will intercept the call coming to the gateway and dispatch it to multiple methods and compose the returning values. I have tried to look at the source code but couldn't find where you invoke the method info for the application service endpoints. Can you direct me to the necessary part?

    If you mean where do the auto-api controllers are configured, it is under the module service configuration. You can also modify your endpoints in the Http.Api project and add your middleware in HttpApi.Host (or .Web) module. Abp uses UseConfiguredEndpoints middleware for the endpoints.

  • User Avatar
    0
    cangunaydin created

    Hello again sorry for my late response. From the reply I didn't understand some parts.

    You can design it as a single request posting data to multiple microservices using the aggregate pattern. It should work fine.

    Let's assume i am doing a call to the gateway posting data for Product Entity. if you look at the image.

    I do one post to the gateway then i need to seperate (or decompose) it to 3 different microservice, how you are going to do it with aggregator pattern? As i know it Ocelot can not make it.(correct me if i am wrong). Can KrakenD do that? cause when I look at the docs i couldn't see any example for that. https://www.krakend.io/docs/endpoints/response-manipulation/#merge-example

    It is not caching, it is data duplication. You can also apply caching on it.

    What I wanted to say over here is if you do data duplication, some service needs to own it.Then Owner (Microservice) can use it in its bounded context for some kind of behavior. For ex if you do search microservice and use it for that I agree it is the right way to do. But if you take it somewhere just to read data from, then i believe it becomes caching cause no one owns it.

    Anyway I started to write a viewmodel composition kind of gateway for my purpose. Here is what i have done so far.

    1- I created interface ICompositionHandleService in my project. It inherits IRemoteService 2- Then at the startup, I do find the classes that implements this interface. Registering them to dependency injection container. 3- I have created a class that overrides the AbpServiceConvention. I am creating composition routes over here. sth like this.

    [Dependency(ReplaceServices = true)]
        [ExposeServices(typeof(IAbpServiceConvention), typeof(AbpServiceConvention))]
        public class CompositionServiceConvention : AbpServiceConvention
        {
            private readonly CompositionOptions _compositionOptions;
            private readonly IServiceProvider _serviceProvider;
            public CompositionServiceConvention(IOptions<AbpAspNetCoreMvcOptions> options,
                IConventionalRouteBuilder conventionalRouteBuilder,
                CompositionOptions compositionOptions,
                IServiceProvider serviceProvider) : base(options, conventionalRouteBuilder)
            {
                _compositionOptions = compositionOptions;
                _serviceProvider = serviceProvider;
            }
    
            protected override void ApplyForControllers(ApplicationModel application)
            {
    
                CreateCompositionRoutes();
    
                UpdateCompositionControllers(application);
                
                //original code here.
                RemoveDuplicateControllers(application);
    
                foreach (var controller in GetControllers(application))
                {
                    var controllerType = controller.ControllerType.AsType();
    
                    var configuration = GetControllerSettingOrNull(controllerType);
    
                    // rest is same
                }   
    }
    

    so to examplify it let's assume that i have an interface

    public interface IProductDetailService
    {
        Task<ProductCompositionDto> GetAsync(Guid id);
    }
    
     public class ProductCompositionDto : CompositionViewModelBase
        {
            public ProductDto Product { get; set; }
    
            public ProductPriceDto ProductPrice { get; set; }
    
        }
    

    and two service one is on **Sales ** Namespace.

     namespace Sales;
     
     public class ProductCompositionService : CompositionService, 
            IProductDetailService,
            ICompositionHandleService,
            IRemoteService,
            ITransientDependency
        {
            private readonly IProductPriceAppService _productPriceAppService;
            public ProductMergeCompositionService(IProductPriceAppService productPriceAppService)
            {
                _productPriceAppService = productPriceAppService;
            }
    
            public async Task<ProductCompositionDto> GetAsync(Guid id)
            {
                var result = CompositionContext.HttpRequest.GetComposedResponseModel<ProductCompositionDto>();
                result.ProductPrice = await _productPriceAppService.GetAsync(id);
                return result;
            }
    		
        }
    

    the other one is on **Marketing ** Namespace

    namespace Marketing;
    public class ProductCompositionService : CompositionService,
                IProductDetailService,
             ICompositionHandleService,
            IRemoteService,
            ITransientDependency
        {
            private readonly IProductAppService _productAppService;
            public ProductMergeCompositionService(IProductAppService productPriceAppService)
            {
                _productAppService = productPriceAppService;
            }
    
            public async Task<ProductCompositionDto> GetAsync(Guid id)
            {
                var result = CompositionContext.HttpRequest.GetComposedResponseModel<ProductCompositionDto>();
                result.Product = await _productAppService.GetAsync(id);
                return result;
            }
        }
    

    since these classes shares the same name and same interface they are gonna be duplicated as 2 routes (api endpoints). To avoid that i remove one of them in CompositionServiceConvention class. I managed to register this as an api controller.

    And as the last step I have added IAsyncActionFilter to my project. To handle the requests for composition routes. here is how i write the action filter.

     public class CompositionOverControllersFilter : IAsyncActionFilter, ITransientDependency
        {
            CompositionOptions _compositionOptions;
            public CompositionOverControllersFilter(CompositionOptions compositionOptions)
            {
                _compositionOptions = compositionOptions;
            }
    
            public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
            {
                if (context.HttpContext.GetEndpoint() is RouteEndpoint endpoint)
                {
                    Debug.Assert(endpoint.RoutePattern.RawText != null, "endpoint.RoutePattern.RawText != null");
                    var rawTemplate = endpoint.RoutePattern.RawText;
                    var templateHttpMethod = context.HttpContext.Request.Method;
                    var compositionRouteMatched = _compositionOptions.CompositionRouteRegistry.Where(o => o.Route == rawTemplate && o.Method.Method == templateHttpMethod).FirstOrDefault();
    
                    if (compositionRouteMatched != null)
                    {
                        var compositionHandler = new CompositionHandler();
                        var viewModel = await compositionHandler.HandleComposableRequest(context.HttpContext, compositionRouteMatched);
                        if (viewModel != null)
                            context.Result = new ObjectResult(viewModel);
                        else
                            context.Result = new OkResult();
                        return;
    
                    }
                }
    
                await next();
            }
    
        }
    

    and it works fine as you can see if the route is matched i am handling the request on compositionHandler class. Over there I use some reflections. Calling the Sales.ProductCompositionService and Marketing.CompositionService classes GetAsync(Guid id) methods and waiting for them to finish and composing the result.

    There are 3 problems i am facing here. I would be so glad if you can help me out with those problems.

    1. When i call two methods from different classes sometimes i got this error. (not all the time)

    2022-10-13 00:46:31.738 +02:00 [ERR] There is already a database API in this unit of work with given key: Volo.Abp.PermissionManagement.EntityFrameworkCore.IPermissionManagementDbContext_Server=(LocalDb)\MSSQLLocalDB;Database=MarketPlace;Trusted_Connection=True Volo.Abp.AbpException: There is already a database API in this unit of work with given key: Volo.Abp.PermissionManagement.EntityFrameworkCore.IPermissionManagementDbContext_Server=(LocalDb)\MSSQLLocalDB;Database=MarketPlace;Trusted_Connection=True at Volo.Abp.Uow.UnitOfWork.AddDatabaseApi(String key, IDatabaseApi api)

    it seems like this is related with unitofwork but since i am invoking the methods with reflection i am not expecting for abp to create a unitofwork. Could it be unit of work is created when i call these 2 methods by reflection?

    1. As you can see after i composed the viewmodel I return ObjectResult and terminating the middleware. Is this the right way to do it? What is the response that normally abp should return? And how it works for abp if i call an endpoint from razor page / mvc. Should it be still ObjectResult? (is this gonna break the things.)
    2. Is there any modelbinding helper that abp uses already in its framework? I have tried couple of things to bind the httprequest to my model but i couldn't make it work with methods expects 2 or multiple parameters. if i have an interface like this.
    Task CreateAsync(Guid id, CreateProductDto input) //not working in this case
    

    i couldn't bind it to the CreateProductDto complex type. don't know why. But if i have a case like this.

    Task CreateAsync(CreateProductDto input) //working in this case
    

    here is the code that i use.

    public class RequestModelBinder:ISingletonDependency
    {
        IModelBinderFactory modelBinderFactory;
        IModelMetadataProvider modelMetadataProvider;
        IOptions<MvcOptions> mvcOptions;
    
        public RequestModelBinder(IModelBinderFactory modelBinderFactory, IModelMetadataProvider modelMetadataProvider, IOptions<MvcOptions> mvcOptions)
        {
            this.modelBinderFactory = modelBinderFactory;
            this.modelMetadataProvider = modelMetadataProvider;
            this.mvcOptions = mvcOptions;
        }
          public async Task<object> Bind(HttpRequest request,Type type) 
        {
            //always rewind the stream; otherwise,
            //if multiple handlers concurrently bind
            //different models only the first one succeeds
            request.Body.Position = 0;
    
            var modelType = type;
            var modelMetadata = modelMetadataProvider.GetMetadataForType(modelType);
            var actionContext = new ActionContext(
                request.HttpContext,
                request.HttpContext.GetRouteData(),
                new ActionDescriptor(),
                new ModelStateDictionary());
            var valueProvider =
                await CompositeValueProvider.CreateAsync(actionContext, mvcOptions.Value.ValueProviderFactories);
    
    
            var modelBindingContext = DefaultModelBindingContext.CreateBindingContext(
                actionContext,
                valueProvider,
                modelMetadata,
                bindingInfo: null,
                modelName: "");
    
            modelBindingContext.Model = Activator.CreateInstance(type);
            modelBindingContext.PropertyFilter = _ => true; // All props
    
            var factoryContext = new ModelBinderFactoryContext()
            {
                Metadata = modelMetadata,
                BindingInfo = new BindingInfo()
                {
                    BinderModelName = modelMetadata.BinderModelName,
                    BinderType = modelMetadata.BinderType,
                    BindingSource = modelMetadata.BindingSource,
                    PropertyFilterProvider = modelMetadata.PropertyFilterProvider,
                },
                CacheToken = modelMetadata,
            };
    
            await modelBinderFactory
                .CreateBinder(factoryContext)
                .BindModelAsync(modelBindingContext);
    
            return Convert.ChangeType(modelBindingContext.Result.Model,type);
        }
    

    it was a long message, i hope i can explain the things :) Thanks for reading and assistance

Made with ❤️ on ABP v9.1.0-preview. Updated on November 01, 2024, 05:35