I'm trying to instantiate a WebClient inside a new WP8.1 project but for an unknown reason there is no WebClient class that I can instantiate.
For now I'll use HttpClient, but that is more lazy when it comes to getting data from server.
Could you please give me a suggestion?
HttpClient is the mostly like as WebClient, you can encapsulate by yourself. Also, you can follow the thread for more of the HttpClient.
Related
I have been having issues registering HttpClient in my project. How can I do this?. I injected HttpClient in multiple classes and I need to register it to work for the multiple constructors.
It will have error for using container.Register<HttpClient>(); directly when I test.
System.ArgumentException: 'For the container to be able to create HttpClient it should have only one public constructor: it has 3
I find a workaround based on using below code:
container.Register<HttpClient>(()=>new HttpClient(),Lifestyle.Scoped);
based on
Registering a type with multiple constructors and string dependency in Simple Injector
However, I advice that you use the built-in IHttpClientFactory in asp.net core:
The IHttpClientFactory can be registered by calling the services.AddHttpClient() in Startup.ConfigureServices method.
services.AddHttpClient();
https://learn.microsoft.com/nl-nl/aspnet/core/fundamentals/http-requests?view=aspnetcore-3.0#basic-usage
According to Microsoft, the best practice for an HttpClient is to maintain a singleton version of an HttpClient (paraphrasing, but that's the upshot. Don't dispose of it immediately). My own testing has show that there are definite advantages to a single instance when doing massive Http operations over recreating an HttpClient for every message. So, naturally, it makes sense to place the HttpClient in a DI container.
// Initialize the HTTP client.
HttpClient httpClient = new HttpClient();
httpClient.Timeout = Timeout.Infinite;
httpClient.BaseAddress = new Uri("https://localhost");
serviceCollection.AddSingleton(httpClient);
The problem is that I'm getting warnings from StyleCop: CA2000: Dispose objects before losing scope. Obviously I can suppress, but this bothers me because there are other IDisposable objects that may want to be put in the DI container. Is this warning valid when using a DI pattern? Are there any tricks to dealing with it?
Same issue , same thoughts.
What you can do is assign it to a field
eg this.httpClient = new HttpClient();
this is probably not a bad idea anyway for singletons so their is a clear owner outside IOC .
I am trying to pass monitoring/tracing information through all my external calls in my java application.
To make it transparent, I'm trying to use byte-buddy but have some troubles getting it to work.
To trace every incoming (http) request, I intercept HttpServlet.service(), extract the token header from the HttpServletRequest and put it in a static ThreadLocal in a class named TokenHolder.
To trace every outgoing (http) request, I intercept HttpURLConnection and add the token header I get from the same ThreadLocal (TokenHolder).
The problem I have is that TokenHolder seems to be initialized twice and my 2 interceptors are not writing-to/reading-from the same ThreadLocal and I can't find a way to do it.
I suppose the problem is that HttpURLConnection lives in the bootclasspath while the servlet API does not.
Bonus question: is it possible to intercept URL.openConnection()? That was my first idea but I never could do it because I suppose the URL class is loaded before the agent (because of URLClassLoader) but I don't know if there are workarounds to that.
Yes, you can register a RedefinitionStrategy where Byte Buddy transforms previously loaded classes. To do so, you do however need to avoid adding methods or fields. This can typically be done by using Advice only.
You are also right that classes need to live on the bootstrap loader. You can inject classes into the bootstrap loader by placing them in a jar and using the designated method in the Instrumentation interface.
I'm wondering whether sleuth has reactive WebClient instrumentation supported.
I did't find it from the document:
Instruments common ingress and egress points from Spring applications (servlet filter, async endpoints, rest template, scheduled actions, message channels, Zuul filters, and Feign client).
My case:
I may use WebClient in either a WebFilter or my rest resource to produce Mono.
And I want:
A sub span auto created as child of root span
trace info propagated via headers
If the instrumentation is not supported at the moment, Am I supposed to manually get the span from context and do it by myself like this:
OpenTracing instrumentation on reactive WebClient
Thanks
Leon
Even though this is an old question this would help others...
WebClient instrumentation will only work if new instance is created via Spring as a Bean. Check Spring Cloud Sleuth reference guide.
You have to register WebClient as a bean so that the tracing instrumentation gets applied. If you create a WebClient instance with a new keyword, the instrumentation does NOT work.
If you go to Sleuth's documentation for the Finchley release train, and you do find and you search for WebClient you'll find it - https://cloud.spring.io/spring-cloud-static/Finchley.RC2/single/spring-cloud.html#__literal_webclient_literal . In other words we do support it out of the box.
UPDATE:
New link - https://docs.spring.io/spring-cloud-sleuth/docs/current/reference/html/integrations.html#sleuth-http-client-webclient-integration
let me paste the contents
3.2.2. WebClient
This feature is available for all tracer implementations.
We inject a ExchangeFilterFunction implementation that creates a span
and, through on-success and on-error callbacks, takes care of closing
client-side spans.
To block this feature, set spring.sleuth.web.client.enabled to false.
You have to register WebClient as a bean so that the tracing
instrumentation gets applied. If you create a WebClient instance with
a new keyword, the instrumentation does NOT work.
I created some POX services using the REST Starter kit.
At first, it was a little complicated to create the unit tests for the service layer, but in the end, it was well designed and I succeed in mocking the context and set expectations.
But, I'm starting in with the client side now, and I'm having some problems figuring out how to mock things. It's not so straight forward.
So, I have this sample method that post via HTTP some data using a datacontract and XML as transport.
public class ServiceClient: IService
{
private const string uri_template = "http://{0}:{1}/SomeService.svc/";
private readonly HttpClient http = new HttpClient();
public ServiceClient(string host, int port)
{
http.BaseAddress = new Uri(string.Format(uri_template , host, port));
}
public void Create(MyDataContract my_data_contract)
{
var content = HttpContentExtensions
.CreateDataContract(
my_data_contract,
Encoding.Default,
"text/xml",
null);
var response = http.Post("Create", content);
if (response.StatusCode != HttpStatusCode.Created) {
throw new Exception("something is not right");
}
}
}
This method is working and indeed posting the data and serializing correctly.
What I want to do, is to unit test it.
My questions are:
How do I make stubs/mocks for HttpContextExtensions knowing that it does not implement any interface?
And for HttpClient? this is worst since it is full of extension methods defined elsewhere (Post and the like methods are extensions).
In 2. I guess I can stick to 'Send' and it's overloads, but then is the same problem as in 1
What I was thinking to do, is to extract interfaces for HttpContextExtensions and HttpClient, make a children for each one and implement the interfaces delegating to the parent, and then using the interfaces in my code.
But that's a lot of work IMHO.
I'm using RhinoMocks as my mocking framework so I can't mock/stub concrete classes, and I would like to stick to it, because I really think that mocking concrete classes is not very elegant.
So, is there a cleaner/faster/smarter way to unit test code like the above?
PD: This is for WCF Starter Kit preview 2
If you really want to mock that code, an approach that could work for this scenario is to receive an HttpClient instance in the ServiceClient class. The HttpClient class contains a processing pipeline that you can customize with custom handlers. For your tests, you can basically inject a handler in that httpclient instance to return a mocked response to the test before the real service is called in the last handler (Transport Stage). Take a look at this post to get an idea about how this can be implemented,
http://weblogs.asp.net/cibrax/archive/2009/03/18/negotiating-a-saml-token-for-rest-clients-with-httpclient.aspx
Regards,
Pablo.
I wrote most of the HttpClient code. Pablo's suggestion is what I did in the unit tests -- see FixedTransport.cs in the source zip.