How do you deal with CA2000 (Dispose of IDisposable Objects) when the objects are placed in a Dependency Injection container? - singleton

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 .

Related

How to use both IHttpClientFactory and Typed HttpClient?

I have a typed HttpClient and (let's say) another service/class that uses IHttpClientFactory to get a HttpClient instance.
To register IHttpClientFactory, I inject it as services.AddHttpClient(). And to register typed clients, I go with services.AddHttpClient<MyTypedClient>
My question is, do you think there will be a problem if I use both of the use cases. Any impact on HttpMessageHandler pool?
Thanks,
Cem.
Simply, no. You can use whatever you want. IHttpClientFactory handles the collection of HttpMessageHandler instances. When you inject a typed client, what's actually happening is that IHttpClientFactory is invoked, and new HttpClient instance is created, and its handler is set to the either an already created HttpMessageHandler instance or a new instance.
In other words, it's mostly syntactic sugar. IHttpClientFactory is invoked in either case, and it always creates a new HttpClient instance, setting the handler to one that's tracking, based on name. A "typed" client is really just a "named" client, with the type as the name, and all clients are in effect "named" because it's all being stored in a ConcurrentDictionary, where the name is the key.

How to configure NHibernate with SignalR

I want to configure NHibernate only once and reuse the session factory to open different sessions to manipulate database,
however the hubs are considered as transient objects and loose object state when client is initializing another request to the hub. The only way so far that i have read about is to make the objects static in order to reuse it.
Is there some other way of achieving this without making the objects static ?
myConfiguration = new Configuration();
myConfiguration.Configure();
mySessionFactory = myConfiguration.BuildSessionFactory();
mySession = mySessionFactory.OpenSession();
Thank you in advance :)
There is nothing wrong with having Configuration and SessionFactory objects stored in static fields. Sessions should not be shared.
An alternative would be to use a DI container and register them as singletons.

Ninject, Web API and MVC 4 Filter Binding disposing datacontext

I have an issue with my datacontext getting disposed every once in a while in one of my filters attached to my web api controllers. Is this the correct way to setup a filter for my Web API controllers and why does my datacontext get disposed sometimes?
The operation cannot be completed because the DbContext has been disposed.
Global.asax
GlobalConfiguration.Configuration.Filters
.Add(new ApiValidationFilter(kernel.Get<IApiAuthenticationService>()));
kernel.Bind<IDatabaseFactory>()
.To<DatabaseFactory>()
.InScope(q => HttpContext.Current ?? StandardScopeCallbacks.Thread(q));
ApiValidationFilter.cs
public class ApiValidationFilter : System.Web.Http.Filters.IActionFilter
{
private readonly IApiAuthenticationService _apiAuthenticationService;
public ApiValidationFilter(
IApiAuthenticationService apiAuthenticationService)
{
_apiAuthenticationService = apiAuthenticationService;
}
You should be using the Filter binding syntax, then Ninject will handle the the filter lifetime, and it will also handle the constructor injection of the filter.
https://github.com/ninject/ninject.web.mvc/wiki/Filter-configurations
I would also let Ninject handle managing the lifetime of the data conext as well, instead of using a factory.
kernel.Bind<MyContext>().ToSelf().InRequestScope();
Alternatively, if you want better testability you can derive your context from an interface and bind to that. The InRequestScope makes sure the context lives for the entire web request, and it will automatically get disposed when the request is done. You don't have to remember to do so, and there won't be any memory leaks by holding onto a request longer than a single request.
You can see an example here:
ASP.NET MVC 3 and Global Filter Injection
I eventually had to resort to the following, nothing worked.
var apiRepository = new ApiRepository(new DatabaseFactory());
var apiAuthenticationService = new ApiAuthenticationService(apiRepository, new UnitOfWork(new DatabaseFactory()), new ValidationProvider(null));

Managing NHibernate ISession with Autofac

Does anyone have any tips or best practices regarding how Autofac can help manage the NHibernate ISession Instance (in the case of an ASP.NET MVC application)?
I'm not overly familiar with how NHibernate sessions should be handled. That said, Autofac have excellent instance lifetime handling (scoping and deterministic disposal). Some related resources are this article and this question. Since you're in ASP.Net MVC land make sure you also look into the MVC integration stuff.
To illustrate the point, here's a quick sample on how you can use Autofac factory delegates and the Owned generic to get full control over instance lifetime:
public class SomeController
{
private readonly Func<Owned<ISession>> _sessionFactory;
public SomeController(Func<Owned<ISession>> sessionFactory)
{
_sessionFactory = sessionFactory;
}
public void DoSomeWork()
{
using (var session = _sessionFactory())
{
var transaction = session.Value.BeginTransaction();
....
}
}
}
The container setup to get this to work is quite simple. Notice that we don't have to do anything to get the Func<> and Owned<> types, these are made available automatically by Autofac:
builder.Register(c => cfg.BuildSessionFactory())
.As<ISessionFactory>()
.SingleInstance();
builder.Register(c => c.Resolve<ISessionFactory>().OpenSession());
Update: my reasoning here is that, according to this NHibernate tutorial, the lifetime of the session instance should be that of the "unit of work". Thus we need some way of controlling both when the session instance is created and when the session is disposed.
With Autofac we get this control by requesting a Func<> instead of the type directly. Not using Func<> would require that the session instance be created upfront before the controller instance is created.
Next, the default in Autofac is that instances have the lifetime of their container. Since we know that we need the power to dispose this instance as soon as the unit of work is done, we request an Owned instance. Disposing the owned instance will in this case immediately dispose the underlying session.
Edit: Sounds like Autofac and probably other containers can scope the lifetime correctly. If that's the case, go for it.
It isn't a good idea to use your IoC container to manage sessions directly. The lifetime of your session should correspond to your unit of work (transaction boundary). In the case of a web application, that should almost certainly be the lifetime of a web request.
The most common way to achieve this is with an HttpModule that both creates your session and starts your transaction when a request begins, then commits when the request has finished. I would have the HttpModule register the session in the HttpContext.Items collection.
In your IoC container, you could register something like HttpContextSessionLocator against ISessionLocator.
I should mention that your generic error handling should locate the current session and roll back the transaction automatically, or you could end up committing half a unit of work.

How to unit test a WCF Client built with WCF Rest Starter Kit

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.