Configure dependency injection from middleware in dot net core - .net-core

I have a class that calls an external service which requires a token, and this is injected using the Settings class.
Now, depending on the request, I need to use one of two tokens.
I would like to use middleware to look at the incoming request to then configure what is injected into my service, but not sure this is possible?
Can I configure the DI from middleware?

I'm not sure that you can configure Dependency Injection from within middleware because DI is done (if you're using the DI system supplied with .NET Core) during the Container setup faze (take a look at your startup.cs class).
I have a class that calls an external service which requires a token, and this is injected using the Settings class.
Now, depending on the request, I need to use one of two tokens
Could you not get both tokens and pass them into your middleware's constructor? I did something similar (passing a configuration object into the middleware constructor) when I was creating my OWASP secure headers middleware (it's part two in a now finished multipart series).
Could you take in the config and switch on something found within the request during your middleware's Invoke task?

Related

Does a call to MapRazorPages() constitute a call to UseEndpoints()?

According to the documentation for UseRouting(), we must call UseEndpoints() afterward:
A call to UseRouting(IApplicationBuilder) must be followed by a call to UseEndpoints(IApplicationBuilder, Action) for the same IApplicationBuilder instance.
But in some code samples (e.g. here) I see UseRouting() calls with UseEndpoints() omitted and MapRazorPages() used instead. Is this safe?
I entered this query into ChatGPT:
What is the difference between App.MapRazorPages and App.UseEndpoints(Sub(Routes) Routes.MapRazorPages)?
...and it returned this helpful answer:
App.MapRazorPages is a method that configures the routing for Razor pages in an ASP.NET Core application. It adds a default route for all Razor pages, which is {page}/{handler?}, where page is the name of the Razor page and handler is the name of an optional handler method defined within the page.
App.UseEndpoints is a method that enables you to specify a pipeline of middleware that will be executed when a request is received by the application. Within the lambda expression provided to UseEndpoints, you can call MapRazorPages to add a route for Razor pages to the pipeline.
So, in short, App.MapRazorPages is a specific method that configures routing for razor pages, while App.UseEndpoints is a more general method that allows you to specify a pipeline of middleware and register various types of endpoints, including razor pages, in the application.
All well and good. Very nice. But what about the admonition from the documentation, that we must call UseEndpoints() at some point after we call UseRouting()? Is it safe to rely on only a call to MapRazorPages() to fulfill that requirement?
This answer seems to indicate so, but I'd like to make sure before I go stringing things together that I don't fully understand.
---EDIT---
Well, go figure.
I consulted the almighty ChatGPT on this one (should've done that at first, I guess) and he boomed down:
No, it is not safe to rely on a call to MapRazorPages() as a substitute for the required call to UseEndpoints().
UseRouting() is used to enable routing in an ASP.NET Core application. It sets up the routing system and prepares the app to handle incoming requests.
MapRazorPages() is an extension method that can be used to configure Razor pages in an ASP.NET Core application. It adds a Razor pages endpoint to the application's endpoint routing table, which allows the app to handle requests for Razor pages.
UseEndpoints() is used to define the endpoints for an ASP.NET Core application. It adds a route to the application's endpoint routing table for each endpoint defined within the lambda passed to it.
So, while MapRazorPages() can be used to configure razor pages and add a corresponding endpoint to the application's endpoint routing table, it cannot be used as a substitute for UseEndpoints(). UseEndpoints() is required to properly define the endpoints for an ASP.NET Core application and handle incoming requests.
So there we have it. But should we trust it? I'm a little bit wary, perhaps because I tend to prefer to live on the edge and not allow myself to be lulled into complacency by The Matrix.
Can someone corroborate?
It differs in different .NET versions.
For example, in .NET 5, you have to call app.UseEndpoints() to register routing. However, in .NET 6 you can register routes with a call to app.MapRazorPage() directly, leaving out both app.UseRouting() and app.UseEndpoints(). This is documented here.
Apps typically don't need to call UseRouting or UseEndpoints. WebApplicationBuilder configures a middleware pipeline that wraps middleware added in Program.cs with UseRouting and UseEndpoints. However, apps can change the order in which UseRouting and UseEndpoints run by calling these methods explicitly.

Should I explicitly use the httpClientFactory class as a recommendation when creating and using typed http clients and DI in .NET 6?

I am using NSwag to create typed http clients with interfaces and registering them with DI using AddHttpClient() and injecting them where they need to be used in calling APIs.
I read about some limitations of the httpclient class such as socket exhaustion & not detecting dns changes and the recommendation to use httpClientFactory and its CreateClient method to create httpclients to alleviate these limitations.
I haven't used the httpClientFactory in a new app that I started working on.
It's using .NET 6 and my question is.. Is httpClientFactory still a recommended way to use explicitly or is it used implicitly in DI because of the use of AddHttpClient() and I don't have to worry about those limitations? I didn't see a clear direction on how to use typed clients, or http clients in general, and whether .NET 6 has introduced improvements in this area.
HttpClient can be injected only inside typed clients
For other usages IHttpClientFactory is required
As the docs state for either case underlying infrastructure (HttpMessageHandler) is managed by the framework so in general you don't need to worry about it (unlike when creating and managing HttpClients manually which could lead to incorrect disposal).
Using typed clients registered via HttpClientFactoryServiceCollectionExtensions.AddHttpClient<TClient> handles IHttpClientFactory for you. When adding typed client internally AddTypedClientCore is called which registers resolver via AddTypedClientCore, which uses IHttpClientFactory:
IHttpClientFactory httpClientFactory = s.GetRequiredService<IHttpClientFactory>();
HttpClient httpClient = httpClientFactory.CreateClient(builder.Name);
ITypedHttpClientFactory<TClient> typedClientFactory = s.GetRequiredService<ITypedHttpClientFactory<TClient>>();
return typedClientFactory.CreateClient(httpClient);
Related:
Make HTTP requests using IHttpClientFactory in ASP.NET Core
Use IHttpClientFactory to implement resilient HTTP requests

How to access dependency injection container in Symfony 4 without actual injection?

I've got a project written in Symfony 4 (can update to the latest version if needed). In it I have a situation similar to this:
There is a controller which sends requests to an external system. It goes through records in the DB and sends a request for every row. To do that there is an MagicApiConnector class which connects to the external system, and for every request there is a XxxRequest class (like FooRequest, BarRequest, etc).
So, something like this general:
foreach ( $allRows as $row ) {
$request = new FooRequest($row['a'], $row['b']);
$connector->send($request);
}
Now in order to do all the parameter filling magic, the requests need to access a service which is defined in Symfony's DI. The controller itself neither knows nor cares about this service, but the requests need it.
How can my request classes access this service? I don't want to set it as a dependency of the controller - I could, but it kinda seems awkward, as the controller really doesn't care about it and would only pass it through. It's an implementation detail of the request, and I feel like it shouldn't burden the users of the request with this boilerplate requirement.
Then again, sometimes you need to make a sacrifice in the name of the greater good, so perhaps this is one of those cases? It feels like I'm "going against the grain" and haven't grasped some ideological concept.
Added: OK, the full gory details, no simplification.
This all is happening in the context of two homebrew systems. Let's call them OldApp and NewApp. Both are APIs and NewApp is calling into the OldApp. The APIs are simple REST/JSON style. OldApp is not built on Symfony (mostly even doesn't use a framework), the NewApp is. My question is about NewApp.
The authentication for OldApp APIs comes in three different flavors and might get more in the future if needed (it's not yet dead!) Different API calls use different authentication methods; sometimes even the same API call can be used with different methods (depending on who is calling it). All these authentication methods are also homebrew. One uses POST fields, another uses custom HTTP headers, don't remember about the third.
Now, NewApp is being called by an Android app which is distributed to many users. Android app actually uses both NewApp and OldApp. When it calls NewApp it passes along extra HTTP headers with authentication data for OldApp (method 1). Thus NewApp can impersonate the Android app user for OldApp. In addition, NewApp also needs to use a special command of OldApp that users themselves cannot call (a question of privilege). Therefore it uses a different authentication mechanism (method 2) for that command. The parameters for that command are stored in local configuration (environment variables).
Before me, a colleague had created the scheme of a APIConnector and APICommand where you get the connector as a dependency and create command instances as needed. The connector actually performs the HTTP request; the commands tell it what POST fields and what headers to send. I wish to keep this scheme.
But now how do the different authentication mechanisms fit into this? Each command should be able to pass what it needs to the connector; and the mechanisms should be reusable for multiple commands. But one needs access to the incoming request, the other needs access to configuration parameters. And neither is instantiated through DI. How to do this elegantly?
This sounds like a job for factories.
function action(MyRequestFactory $requestFactory)
{
foreach ( $allRows as $row ) {
$request = $requestFactory->createFoo($row['a'], $row['b']);
$connector->send($request);
}
The factory itself as a service and injected into the controller as part of the normal Symfony design. Whatever additional services that are needed will be injected into the factory. The factory in turn can provide whatever services the individual requests might happen to need as it creates the request.

How do I get access to Castle DynamicProxy generation options within MOQ?

Does MOQ give access to Castle's DynamicProxy generation? Or are there configurable static methods or something in the Castle namespace that would allow me to tune MOQ's proxy gen behavior?
Some Background
I am Mocking a WCF Service endpoint (IWhatever). WCF automatically adds Async call back options for methods (e.g. IWhatever.DoWork() is also realized as IWhatever.DoWorkAsync()).
I'm looking to use the Mock<IWhatever> object while self-hosting this service mock'd; basically spoof this external web service to my system. However, when [self-hosted] WCF tries to create a DoWorkAsync() method; it already exists... which ultimately throws errors when opening the self-hosted/mock'd IWhatever endpoint. ((NOTE: I don't have access to original contract to use directly)).
Sooo.. looks like Castle DynamicProxy allows for one to define which methods should be generated (see: http://kozmic.net/2009/01/17/castle-dynamic-proxy-tutorial-part-iii-selecting-which-methods-to/). I was thinking I would use to not intercept calls on methods ending with "[...]Async". However I don't see where I would add this customization rule in the proxy generation within MOQ; hence my question.

Rest service .net operation contracts during runtime

Is it possible to add operation contracts to a rest service during the runtime?
For instance we have a service which is available under the endpoint: www.mywebsite.com has already one operationContract: getName.
But now I want to add during the runtime two additional operationContracts: like getAdress and GetNumber.
The main problem is how to let clients to know about new service contracts.
I think you can add new service endpoints at runtime by creating ServiceHost instances. Service will listenting to some different addresses. Those endpoints will use different service contracts (interfaces).
I don't think you will construct and implement interfaces dynamically (but you can in .net). You will probably use some predefined interfaces. In this case you should inform clients somehow about new service contract and address. To pass and consume such metadata you can:
1) Use duplex methods (service to client call direction) of some 'static' maintenance service - to bring service metadata to client in custom format;
2) Use periodical client calls (polling) to this maintenance service - for same purpose;
3) Use periodical web scanning (by address range) and parse wsdl to build client proxy at runtime. You can run "svcutil /sc ..." at runtime to generate code or use custom technic (this or this can help);
4) Use intermediate service to orchestrate both service and clients (complex but powerful approach, this can help);
5) Use wcf discovery in addition (not an easy way too);
6) Use combination of those methods.
p.s. You can use one interface but inform client when service supports (implements) certain method. It would be the easiest way.

Resources