MinimalApi Registration for Transient Lifetime Class-based Endpoints #60194
Unanswered
nquandt
asked this question in
Show and tell
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I have been blown away by the performance and scalability of the MinimalApi implementation. Though I've found that the registration strategy gives me paralysis by indecision and also feels somewhat anti-OOP. I don't know if I want to keep my endpoints in the Program.cs file or set them up as extensions methods, but regardless the only example I've seen from the MS-Docs has been to register with a static method or
Func<>
delegate.Working on many digital product driven applications I tend to want all of my functionality baked into standard DI classes. So how can I achieve this with MinimalApi?
I saw that within the code that re-swizzles delegates there is an option to pass an instance method with a delegate target. Though this instance seems to be a static object created outside of DI, and is really just for registering the method as far as I could tell.
What I would like is a pattern that allows we to register a Class and Method such that the class is resolved by DI and the method is ran for that instance to handle a route.
What I built: Femur.AspNetCore.Endpoints
I've slowly been getting my ideas down on paper and this was the first that I felt was worth sharing. This package exposes an extension method for registering a class and mapping the instance method. I do this by generating a delegate at runtime based on the options provided in the extension method. Because the standard AspNetCore implementation supports
[FromServices]
, I take the signature of my instance method and generate a static method+delegate of the same signature PLUS adding a[FromServices] MyClass instance
.All attributes from the parameters are copied over, and all attributes on the method are copied to the new method. Meaning AspNetCore can still infer meta data and setup binding as expected. More details are in the README.md of my repo and the code is available for review.. I did publish it to Nuget incase anyone wants to use it, though I have not tested extensively, only for the cases in which I need, which are more basic "GET" this, "POST" this, with JSON. query and headers.
Usage:
In my repo README I also mention ways this pattern could probably be improved or applied in a more practical situation, such as putting the routepattern and methods inside the class code instead of still at the endpoint registration, though I believe that is more of a concern for the implementers of this pattern, and is much simpler to setup now that this extension method exists.
Here was the output of running FastEndpoints benchmark runner with the addition of my tool.
Beta Was this translation helpful? Give feedback.
All reactions