Why is ASP.NET Web Api's Dependency Resolver being disposed? - c#

I have a custom IDependencyResolver:
internal class NinjectResolver : IDependencyResolver
{
private IKernel _kernel;
internal NinjectResolver(params ApplicationModule[] modules)
{
_kernel = new StandardKernel(modules);
}
public IDependencyScope BeginScope()
{
return this;
}
public object GetService(Type serviceType)
{
return _kernel.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
return _kernel.GetAll(serviceType);
}
protected void Dispose(bool disposing)
{
if(disposing)
{
if(_kernel != null && !_kernel.IsDisposed)
{
_kernel.Dispose();
_kernel = null;
}
}
}
public void Dispose()
{
Dispose(true);
GC.SuppresFinalize(this);
}
}
I am registering it like this:
public static void RegisterModules(HttpConfiguration configuration, params ApplicationModule[] modules)
{
_resolver = new NinjectResolver(modules);
configuration.DependencyResolver = _resolver;
}
Everything seems to work fine at the beginning. However, after some minutes (see NOTE) my NinjectResolver is disposed, and therefore begins to throw NullPointerException when trying to resolve a type (this is because I am setting _kernel = null in the Dispose method).
A way to solve this is to keep the reference alive and not set it to null when the resolver is disposed. But why should I?
I mean, why is my resolver getting disposed just like that, from one minute to another? Nowhere in my code am I disposing it explicitly, so it must be the Web Api framework doing it for me.
NOTE: Sometimes it takes a couple of minutes, and sometimes just seconds. It's completely random.

The reason that this class is being disposed is because there is a bug in this class. You are using the NinjectResolver both as resolver and as scope and you are returning the NinjectResolver instance as IDependencyScope by returning it from the BeginScope() method. The BeginScope() method is called once per request by the Web API infrastructure and Web API will call IDependencyScope.Dispose() when the request ends. The problem is that you always dispose the kernel when this happens, which means that your kernel will be unusable after the first request.
A quick fix is to just don't dispose the kernel at all. Since this kernel will live for the duration of the complete application, not disposing the kernel is typically not a problem.

Related

How to dispose the data provider instance using HttpClient?

I have created my data provider using Repository Pattern.
First, I designed a base repository interface as following:
internal interface IGenericRepository<T, in TResourceIdentifier>
{
Task<IEnumerable<T>> GetManyAsync();
Task<T> GetAsync(TResourceIdentifier id);
Task PutAsync(T model);
Task<T> PostAsync(T model);
Task DeleteAsync(TResourceIdentifier id);
}
Then I implemented it:
public class GenericRepository<T, TResourceIdentifier> : IDisposable, IGenericRepository<T, TResourceIdentifier>
where T : class
{
private bool _disposed;
protected HttpClientHelper<T, TResourceIdentifier> Client;
protected GenericRepository(string addressSuffix)
{
Client = new HttpClientHelper<T, TResourceIdentifier>(Properties.Settings.Url, addressSuffix);
}
public async Task<IEnumerable<T>> GetManyAsync()
{
return await Client.GetManyAsync();
}
// All other CRUD methods and dispose
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if(_disposed || !disposing) return;
if(Client != null)
{
var mc = Client;
Client = null;
mc.Dispose();
}
_disposed = true;
}
}
Then I created custom repository interface for each of my entities. For example:
internal interface IOrderRepository : IGenericRepository<Order, int>
{
Task<IEnumerable<Order>> GetOrderBySomeConditionAsync(string condition );
}
And finally, I implemented the custom repository:
public class OrderRepository : GenericRepository<Order, int>, IOrderRepository
{
public OrderRepository(string addressSuffix) : base(addressSuffix)
{
}
public async Task<IEnumerable<Order>> GetOrderBySomeConditionAsync(string condition)
{
//get all the orders (GetManyAsync()) and then returns the ones meeting the condition
}
}
Note that HttpClientHelperuses HttpClient and needs to be disposed manually.
I have created a MVC web application and have defined the repositories at the class level as such:
IOrderRepository _orderRepository = new OrderRepository();
When I call _orderRepository in my CRUD operations, it does not hit dispose after its use. In order to fix that I have ended up implementing like this:
private async Task<IEnumerable<OrderViewModel>> GetOrders()
{
using(var orderRepository = new OrderRepository())
return await orderRepository.GetManyAsync();
}
This would hit the Dispose but is anti pattern.
What am I missing in my implementation that the instance is not disposed on each call?
You should not be disposing HTTPClient after every request.
[https://learn.microsoft.com/en-us/dotnet/architecture/microservices/implement-resilient-applications/use-httpclientfactory-to-implement-resilient-http-requests][1]
As the above link says -
Therefore, HttpClient is intended to be instantiated once and reused
throughout the life of an application. Instantiating an HttpClient
class for every request will exhaust the number of sockets available
under heavy loads. That issue will result in SocketException errors.
Possible approaches to solve that problem are based on the creation of
the HttpClient object as singleton or static, as explained in this
Microsoft article on HttpClient usage.
Writing a Dispose method in your generic repository does not mean it will be invoked automatically, whenever you feel like it should. It's intended to be invoked individually, hence why you must either use a using statement (as you have shown), or the Dispose method inside your code.
Alternatively, you can leave that job for the garbage collector.
You should also create a finalizer in your generic repository, if you're convinced on using GC.SuppressFinalize(this);
Read more about that here - When should I use GC.SuppressFinalize()?
As R Jain pointed out, you should also create a static class to hold your HttpClient. You'll have to use HttpResponseMessages for your needs, or HttpContent.
Some more resources to read:
HttpClient single instance with different authentication headers
https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/

Doubts will object registered in IAppBuilder.CreatePerOwinContext() be disposed

i have some doubts will my object be disposed.
I customized Owin flow becauze we use CRM as database and administration, so i registered OrganizationServiceProxy in CreatePerOwinContext()
app.CreatePerOwinContext(CrmConnection.Create);
inherited class from OrganizationServiceProxy
public class CrmConnection : OrganizationServiceProxy
{
private CrmConnection()
: base(new Uri(ConfigurationManager.AppSettings["CrmUri"])
, null
, new ClientCredentials()
{
UserName =
{
UserName = ConfigurationManager.AppSettings["CrmUsername"],
Password = ConfigurationManager.AppSettings["CrmPassword"]
}
}
, null
)
{ }
public static CrmConnection Create()
{
return new CrmConnection();
}
So my doubts are will instance of this object be disposed after request is over?
I did some research and if i got it right every object passed to CreatePerOwinContext() should be of type IDisposable?
every object passed to CreatePerOwinContext() should be of type
IDisposable?
More than should be. Has to Be. Look at the signature of CreatePerOwinContext
public static IAppBuilder CreatePerOwinContext<T>(
this IAppBuilder app,
Func<IdentityFactoryOptions<T>, IOwinContext, T> createCallback
)
where T : class, IDisposable
You can't register anything that doesn't implement IDisposable
So my doubts are will instance of this object be disposed after
request is over?
You can verify this by logging calls to Dispose
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
Debug.WriteLine($"I'm disposing");
}
In addition to #Shoe's logging method, you can verify disposal by creating a WeakReference to your object, waiting for the request to complete, manually calling the garbage collector, then checking WeakReference.Target. As long as nothing else is holding a reference, Target will return null if the object has been collected.
The WeakReference will allow you to hold a reference to an instance of something, but will still allow it to be garbage collected.
Don't do this in production code of course, this is just to proove to yourself that the object was disposed.
The handy thing about this method, is that it will work for any object, even ones that are outside your control where you can't override IDisposable.
var reference = new WeakReference(myIDsiposableInstance, true);
//Make a request, and wait for it to complete
GC.Collect();
GC.WaitForPendingFinalizers();
if(reference.Target == null)
{
//Disposed
}
else
{
//Not Disposed
}
OrganizationServiceProxy derives from ServiceProxy<TService> which implements IDisposable. If neither the derived nor abstract classes implemented IDisposable then it wouldn't be valid as a return value for the Func<T> passed to CreatePerOwinContext (as there is a constraint on T requiring it to implement IDisposable.) This would lead to a compiler error.
The only reasons to worry it isn't being disposed is because you believe there is a bug in the implementation of OWIN that isn't calling the Dispose method or that there is a bug in either Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy or Microsoft.Xrm.Sdk.Client.ServiceProxy<TService> that is not allowing the object to be disposed.

Ninject Factory Extension and Dealing with Memory Leak

This question is more of a "how do I do it?", rather than a "what am I doing wrong?". I have a class which is called QueryProcessor that processes queries (think CQRS). That object is injected into my presenters. The QueryProcessor needs to use the kernel to resolve bindings. Injecting the kernel in, either directly or via a factory, is easy. Doing so without causing a memory leak is the trick.
I have verified using a memory profiler that none of my QueryProcessor objects are being garbage collected. The class looks like this:
public sealed class QueryProcessor : IQueryProcessor, IDisposable
{
private readonly IKernelFactory _container;
private bool _disposed;
public QueryProcessor(IKernelFactory container)
{
_container = container;
}
//[DebuggerStepThrough]
public TResult Process<TResult>(IQuery<TResult> query)
{
var handlerType = typeof(IQueryHandler<,>).MakeGenericType(query.GetType(), typeof(TResult));
dynamic handler = _container.RetrieveKernel().Get(handlerType);
return handler.Handle((dynamic)query);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
private void Dispose(bool disposing)
{
if (disposing && !_disposed)
{
// dispose of stuff here
_disposed = true;
}
}
}
public interface IKernelFactory
{
IKernel RetrieveKernel();
}
My composition root is reasonably straightforward. I am using the factory extension of Ninject.
public void OnLoad(IKernel kernel)
{
// Auto-Register all the validators which are stored in the Service assembly.
AssemblyScanner.FindValidatorsInAssembly(_serviceAssembly).ForEach(
result => kernel.Bind(result.InterfaceType, result.ValidatorType)
);
ManualRegistrations(kernel);
kernel.Bind<IKernelFactory>().ToFactory();
AutoRegisterType(kernel, typeof(IQueryHandler<,>));
AutoRegisterType(kernel, typeof(ICommandHandler<>));
}
As mentioned, the injection is working, but it is leaving a memory leak. How am I supposed to get the Ninject kernel resolving stuff in my QueryProcessor without causing the leak?
Thanks
Update - New Problem
I tried to solve this problem by creating a new kernel with a new module, separate from the main kernel of the Composition Root. These sub-kernels would be created and disposed up, with their lifetimes being tied to that of the QueryProcessors. I hooked it up like this in the main module:
kernel.Bind<IQueryProcessor>().ToMethod(ctx => new QueryProcessor(new StandardKernel(new ProcessorModule(_serviceAssembly)))).InTransientScope();
It works fine before the kernel is disposed of for the first time. But after that, I get the following error message:
Error loading Ninject component ICache
No such component has been registered in the kernel's component container.
Suggestions:
1) If you have created a custom subclass for KernelBase, ensure that you have properly
implemented the AddComponents() method.
2) Ensure that you have not removed the component from the container via a call to RemoveAll().
3) Ensure you have not accidentally created more than one kernel.
Damned if I do, damned if I don't ...
Since your application, not the DI container, is creating the instance it is also responsible for disposing the instance. This scenario can be handled by using the Register, Resolve, and Release pattern.
If you inject the kernel, then you have effectively implemented the service locator anti-pattern. This means your application is explicitly dependent on your DI framework.
Rather than injecting the kernel, you should use an abstract factory as mentioned in the post DI Friendly Framework to handle both creating and releasing the handler instances.
public interface IHandlerFactory
{
dynamic Create(Type handlerType);
void Release(dynamic handler);
}
public interface HandlerFactory
{
private readonly Func<Type, dynamic> handlerMethod;
public HandlerFactory(Func<Type, dynamic> handlerMethod)
{
if (handlerMethod == null)
throw new ArgumentNullException("handlerMethod");
this.handlerMethod = handlerMethod;
}
public dynamic Create(Type handlerType)
{
return handlerMethod(handlerType);
}
public void Release(dynamic handler)
{
IDisposable disposable = handler as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
}
}
Usage
public sealed class QueryProcessor : IQueryProcessor
{
private readonly IHandlerFactory handlerFactory;
public QueryProcessor(IHandlerFactory handlerFactory)
{
if (handlerFactory == null)
throw new ArgumentNullException("handlerFactory");
this.handlerFactory = handlerFactory;
}
//[DebuggerStepThrough]
public TResult Process<TResult>(IQuery<TResult> query)
{
var handlerType = typeof(IQueryHandler<,>).MakeGenericType(query.GetType(), typeof(TResult));
dynamic handler = this.handlerFactory.Create(handlerType);
try
{
return handler.Handle((dynamic)query);
}
finally
{
this.handlerFactory.Release(handler);
}
}
}
Note that if you use this approach, you are not requiring every handler to implement IDisposable, nor does your QueryProcessor unnecessarily need to implement IDisposable.
In your composition root, you just need to implement the handler method and register it as a parameter to your factory.
Func<Type, dynamic> handlerMethod = type => (dynamic)kernel.Resolve(type);
kernel.Bind<IHandlerFactory>().To<HandlerFactory>()
.WithConstructorArgument("handlerMethod", handlerMethod);
Of course, if you are processing your handlers asynchronously you have to keep the instance alive until the end of the request rather than disposing it as soon as the handler.Handle() method returns. If that is the case, I suggest you analyze the source code for WebApi to work out what pattern is used to do that when dealing with the System.Web.Http.ApiController.

Should objects created by an IDisposable that reference their creator dispose of that creator?

I have a class that implements IDisposable according to this pattern because it contains a reference to HttpClient. It looks something like this:
public class CustomServiceClient : IDisposable
{
HttpClient client;
// ...
public ServiceCreatedEntity GetEntity()
{
// ...
}
~CustomServiceClient()
{
this.Dispose(false);
}
private bool disposed = false;
void IDisposable.Dispose()
{
if(!disposed)
{
this.Dispose(true);
GC.SuppressFinalize(this);
disposed = true;
}
}
public void Dispose(bool disposing)
{
if(disposing)
{
// dispose managed resources
client.Dispose();
}
// dispose unmanaged resources - this class has none
}
}
public class ServiceCreatedEntity
{
CustomServiceClient client;
public ServiceCreatedEntity(CustomServiceClient client)
{
this.client = client;
}
// some functions that use client
}
I'm wondering if ServiceCreatedEntity should implement IDisposable and dispose of the CustomServiceClient. I expect that CustomServiceClient will generally have a longer lifetime than ServiceCreatedEntity, and I'm worried that a client will dispose of ServiceCreatedEntity and be confused as to why their CustomServiceClient has been disposed of as well. Any tips would be greatly appreciated!
it's more of a question of what creates what... the creator should (typically) handle the teardown in a request oriented world.
ServiceCreatedEntity should not dispose the client, but if it has a dependency on the client it doesn't hurt to include a IsDisposed property or Disposing event on the client so that ServiceCreatedEntity can verify that the client is not disposed before using it, or just have CustomServiceClient throw an error if being used after disposal.
I'm confused as to why CustomServiceClient has a method that returns ServiceCreatedEntity and yet ServiceCreatedEntity takes CustomServiceClient as a parameter in its constructor.
Generally, if an object is passed in, it should not be disposed in that object. If an object creates an IDisposable it should itself implement IDisposable and dispose of it. For any other circumstances (such as an IoC container, or something fancy), consider the lifespan of the object and when it will be disposed.
Take a look at this question for more information about IDisposable.

Dispose or not dispose injectable instance using Ninject

I have the following code block for configuring Ninject in my solution:
public class NinjectDependencyScope : IDependencyScope
{
private IResolutionRoot resolver;
internal NinjectDependencyScope(IResolutionRoot resolver)
{
Contract.Assert(resolver != null);
this.resolver = resolver;
}
public object GetService(Type serviceType)
{
if (resolver == null)
{
throw new ObjectDisposedException("this", "This scope has already been disposed");
}
return resolver.TryGet(serviceType);
}
public IEnumerable<object> GetServices(Type serviceType)
{
if (resolver == null)
{
throw new ObjectDisposedException("this", "This scope has already been disposed");
}
return resolver.GetAll(serviceType);
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
IDisposable disposable = resolver as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
resolver = null;
}
}
My opinion is that disposable pattern used here, is not neccessary..
IDependencyScope is IDisposable, but I should only cleanup IDisposable members if I am constructing them, but the injected resolver in the constructor does is not owned (created) by my class, and IResolutionRoot does not derive from/implement IDisposable...
Am I right here ?
(check this article about IDisposable pattern for reference)
(edit):
This is in fact a base class, used by the following class, so removing the IDisposable implementation here cannot be done...
public class NinjectDependencyResolver : NinjectDependencyScope, IDependencyResolver
{
private IKernel kernel;
public NinjectDependencyResolver(IKernel kernel)
: base(kernel)
{
this.kernel = kernel;
}
public IDependencyScope BeginScope()
{
return new NinjectDependencyScope(kernel.BeginBlock());
}
}
My experience with Ninject has been that when it comes to managed objects implementing IDisposable, you don't need to worry so much as they will be disposed off eventually.
However, when if you have disposable objects which are wrappers around unmanaged objects (for example a C# class wrapping around an Office Interop Application object), then you need to take greater care as these will be disposed off eventually by Ninject, but you can't reliably say when.
Sometimes you need to clean up these resources quickly, as other parts of your code may rely on these resources being cleaned up already (for example you may be 'using' one of these objects to create a Workbook, and then need to rename the workbook shortly after, by which point you need the Application object to be released).
In this sort of scenario, I may violate DI principle, and just new up the object when I use it, and dispose of it myself.
I guess just test all of this yourself so you know which objects are suitable to use with Ninject, and which aren't and do so accordingly.
I know that this is the case with Autofac. You shouldn't worry about disposing classes that you have resolved from Autofac because it will call dispose for you. I am pretty sure that Ninject would be similar.
The following miminal implimentation is correct (provided that neither this class or a class that derives from it uses UNmanaged resources - which is rarely the case):
public void Dispose() {
IDisposable disposable = resolver as IDisposable;
if (disposable != null) {
disposable.Dispose();
}
resolver = null;
}
See Minimal IDispose implementation for details.
It is optional as the resolver will be correctly disposed with out it - i.e only necessary in the case when you particularly need to control yourself the release of the resources managed by the resovler (what?).

Categories