Given an assembly where I'd have a SomeContext class derived from DbContext and implementing interface ISomeContext, and a SomeService class implementing ISomeService interface, I'd bind the rest of the app's dependencies like this:
kernel.Bind(t => t.FromThisAssembly()
.SelectAllClasses()
.Where(c => !c.Name.EndsWith("Context") && !c.Name.EndsWith("Service"))
.BindAllInterfaces());
Then, given that SomeService has a constructor-injected ISomeContext dependency, with Ninject.Extensions.NamedScope I can define a named scope like this:
kernel.Bind<ISomeService>().To<SomeService>().DefinesNamedScope("ServiceScope");
And then when I say SomeContext lives in the named scope I've just created, like this:
kernel.Bind<ISomeContext>().To<SomeContext>().InNamedScope("ServiceScope");
My understanding is that by doing that, whenever an instance of SomeService gets injected, the SomeContext instance that it received in its constructor will only live for as long as the SomeService instance exists - that is, when SomeService gets garbage collected, SomeContext gets disposed and dies gracefully.
...I have a few questions:
Is this the proper way of scoping a class that implements IDisposable?
If not, then what would be a proper way of scoping a class that is disposable?
If SomeService is injected in another class (turns out it actually is!), doesn't that other class somewhat creates a scope the context lives and dies in? If so, then what's the use of declaring a "named scope" if all it does is give a name to what gets disposed at garbage collection time?
Shortly put, how exactly is the above code ultimately different from not specifying a scope at all?
Note: InRequestScope is irrelevant here, I'm not talking about a Web app. The application is in fact a class library that gets composed when a client VB6 library calls into it; the C# code lives as a global instance in the VB6 library, and the entire C# app gets composed at once. If the context/disposables live for as long as the C# app's global VB6 instance exists, there's something I'm doing wrong - I'd like my connections to be as short-lived as possible, so I believe I can't be injecting contexts just like this, I should instead be injecting factories that spit out a context that only lives for as long as it is needed, and that would be the scope of whoever gets that factory injected... I think I've just answered part of my question here... have I?
Not using a scope, ninject will not call IDispose.Dispose() on the Context.
.InParentScope() on the context makes sure the context is disposed when the object it gets injected into (SomeService) gets garbage collected
--> When SomeService implements INotifyWhenDisposed, the context will get disposed immediately after SomeService gets disposed.
.InNamed scope is good for injecting the same instance of the Context into multiple objects of an object tree.
Also see http://www.planetgeek.ch/2010/12/08/how-to-use-the-additional-ninject-scopes-of-namedscope/
Related
Hey so I have a base class coming from a 3rd party dll, which is dependent on a disposable. Context: IDisposable
public class BaseValidator
{
public BaseValidator(Context context) {}
}
We're trying to move away from tying our classes to these dependencies. So we started relying on providers instead
public interface IContextProvider
{
Context Create();
}
I have a new validator that I'm writing which inherits from the BaseValidator, but I would like it to be dependent on the IContextProvider instead. So I'd like to create the context in the inherited constructor, but I would like to dispose of it in the destructor to prevent memory leaks, However I'm not sure if this is possible.
public class EntityValidator: BaseValidator
{
public EntityValidator(IContextProvider provider) : base(provider.Create())
{
}
~EntityValidator()
{
//I'm not how I can dispose the entity I've passed into it.
}
}
My question is, is there a trick I can use to Capture the variable passed into the base?
Note: I know I can make a work around with an external helper class, but I'm interested if anyone knows how to do this in a more savvy way.
If the BaseValidator class does not expose Context in a public manner, your current design would require you use reflection and knowledge of the internal implementation of BaseValidator to dispose of it, which is of course fragile.
I would instead capture the context using an intermediate constructor:
Context _context;
private EntityValidator(Context context) : base(context)
{
_context = context;
}
public EntityValidator(IContextProvider provider) : this(provider.Create())
{
}
Note, disposing via a finalizer (a.k.a. destructor) is not ideal due to constraints it places on the garbage collector. I'd instead have EntityValidator implement IDisposable
Before, in other language like C++, developpers used to rely on destructors to do a lot of cleaning. It was guaranteed by compiler so it was a strong behavior.
Smart pointer was a good pattern that used this behavior (to implement something like very basic but automatic garbage collection system).
Code was elegant but people used it for a lot of other need. With time a lot of code used to happen in destructor making the debug and readability hard.
IDisposable has been made to force developpers to write explicitely the call to Dispose... This is also useful when you want to Dispose internal resource without your object being destructed. For example in some "Close" method of Stream, where the stream is definitively closed but you can still have reference on steam... and use IsOpen property...
So for me you should not try to hide it. If you depends on code that needs to be Disposed, embrace this dependency... or chose another third party library.
You can simply make the class that need to manipulate Disposable object (BaseValidator) IDisposable too and delegate the need to call to the user.
Usually people that write class implementing IDisposable, in open source project, also write destructor (just in case someone forgot to call Dispose) This is true for a lot of class of .Net framework too (for example Pen() { where nobody thinks to call Dispose on it in some Control drawing events...)
So I would recommend :
Go get the information about if they did it with their classes, if yes they are strong probability they will keep this behavior/code forever. So you can just make your class to inherit IDisposable too, call context.Dispose in your own Dispose implement and that's enough... no need to worry because if your user forgot to call Dispose, the third party do the cleaning. Add a destructor/finalizer on your class only if you have other unmanaged resource to clean too...
Now if they did not, you can just wrap third party "Context" class in your own Context class. Your Context class will have to implement destructor that call Dispose on the instance of third party Context class. And that's it. You can even make your Context class sealed. Your Context class is here to make the behavior of your app as close as if 1) was true and implemented by third party. So this class will be easy to remove later because third party will probably implement finalizer one day (if they are serious). Doing just a sealed wrapper around just one class will avoid some complexity/issue related to how destructors (finallizers) works in .Net : They are all called in any order. Because of this underterministic behavior it makes your code hard to maintain later. For example if third party Context class's finalizer is called before your wrapping class => exception can occured and at a bad time (when gc is doing its stuff) which can make your app crash. Because of all these problems, you better go back to 1)
We have created a singleton object (SsoSettingsProvider ) in which we inject object with lifestyle PerWebRequest (IReservationService in our example it is WCF client). In constructor we use this object to get some data and we place this data in a private field.
public class SsoSettingsProvider : ISsoSettingsProvider
{
readonly LogonSettings _logonSettings;
public SsoSettingsProvider(IReservationService reservationService)
{
_logonSettings = reservationService.GetSSOSettings();
}
}
If we look at possible lifestyle mismatches in Castle Windsor it says:
"Component 'SsoSettingsProvider / ISsoSettingsProvider' with lifestyle
Singleton depends on 'late bound IReservationService' with lifestyle
PerWebRequest This kind of dependency is usually not desired and may
lead to various kinds of bugs."
This info says that there is only possibility, but in this case i think it is not a problem because injected object is not referenced in a field so it can be garbage collected. am i right ?
in this case i think it is not a problem because injected object is not referenced in a field so it can be garbage collected. am i right?
Castle Windsor is warning about Captive Dependencies. The main problem is not so much that instances aren’t garbage collected, but a class will reuse an instance that is not intended for reuse.
Simple example is when you inject a DbContext into a class that is configured as singleton. Although this will result in the DbContext being held alive until its singleton consumer goes out of scope (which typically is when the application ends). A DbContexthowever should not be reused over multiple requests. For one, because it simply isn't thread-safe. On top of that, it gets stale very soon, which causes it to return cached data, instead of re-querying the database.
For this reason we register DbContext typically as Scoped. This does mean however that all its consumers should live at most as long as the DbContext, to prevent it from breaking the application. This is what Castle is warning about.
In your case however you don't store the IReservationService into a private field of SsoSettingsProvider. This would still be a problem, because it would be reasonable to expect that the objects that IReservationService returns do not outlive the IReservationService (otherwise IReservationService would be registered as Singleton). Since from the perspective of SsoSettingsProvider, there is no way it could know whether or not it is safe to store LogonSettings, it is much better to not store it at all.
On top of that, as expressed here, injection constructors should not use their dependencies at all. This leads to slow and unreliable object composition.
So even though you might have analyzed your design and know for sure that this works in your particular case, I would suggest you doing one of the following things:
Store IReservationService as private field in SsoSettingsProvider and call GetSSOSettings only when one of SsoSettingsProvider's members is called and prevent storing LogonSettings. This forces you to make either SsoSettingsProvider scoped or IReservationService singleton. Whether or not IReservationService can be singleton is only something you can find out.
In case SsoSettingsProvider is only interested in LogonSettings, and LogonSettings is a constant value that won't change after the application started, you should inject LogonSettings directly in SsoSettingsProvider's constructor. This simplifies SsoSettingsProvider and pushes loading the LogonSettings to the Composition Root.
I have a class MyBusiness that I register with SimpleInjector
container.RegisterSingleton<MyBusiness>(() => new MyBusiness(Konstants.ConnectionString));
now MyBusiness implements an interface IRepositoryProvider which is like this
public interface IRepositoryProvider{
IReader<Entity> Get<Entity>();
IWriter<Entity> Writer<Entity>();
}
IReader and IWriter both inherit IDisposable and Entity is some database entity, a POCO class if you will, which may be quite many (assume more than 50 entities in the app generated by some tool). MyBusiness provides the implementations of IReader<> and IWriter<> for any entity that is passed as Generic parameter, I do not provide implementation for any IReader<>, IWriter<>
so in code they are used like:
var biz = container.GetInstance<MyBusiness>();
using(var users = biz.Get<User>()){
...
}
Due to the above I cannot use IReader<> and IWriter<> in constructor injection.
public class MyUserController:Controller{
public MyUserController(IReader<User> arg){
}
// other functionality
}
Can the calls for IReader IWriter above be reduced to this
var users = container.GetInstance<IReader<User>>());
so that I can easily use the IReader<> and IWriter<> implementations as dependency injections?
IReader and IWriter both implement IDisposable
Let's start with this: Abstractions should in general not implement IDisposable. By doing so you are leaking implementation details through the abstraction. This means you are violating the Dependency Inversion Principle, which states:
Abstractions should not depend on details. Details should depend on abstractions.
You are leaking implementation details, because it's typically unlikely that all implementations of that abstraction have resources they need to dispose. For instance:
You are likely to have mock or fake implementations that don't require disposal.
If you create a decorators or interceptor for such abstraction, they typically not have any resources they need to dispose.
Still, since the client expects dispose to actually dispose 'the real thing', those decorators and other implementations are forced to delegate the call through to any wrapped call.
But what if the decorator does get an instance injected through constructor injection. Does it know how whether or not that dependency can be disposed or not? Perhaps it has a long lifestyle and disposing it actually breaks the system.
The solution is to remove IDisposable from the abstraction. This typically makes your application code much simpler, because the client code is not able to call Dispose anymore. This means less code to test, and less things to go wrong (because someone called dispose while he shouldn't).
This does mean however, that we should move the responsibility of disposing that instance, and this is typically what Dependency Injection gives us. It gives us a central place in the application (called the Composition Root) that exactly knows when to dispose what.
Typically, when using a DI Container, the solution is to register such type with a Scoped lifestyle. This means that the instance lives for a certain amount of time. It is than the DI Container how is in control of calling Dispose on your behalf, once the class's lifetime ends.
With Simple Injector, this is typically done as follows:
container.Register(typeof(IReader<>), typeof(ReaderImpl<>), Lifestyle.Scoped);
This means that you can safely inject IReader<User> in the MyUserController, without the MyUserController having to worry about disposal and Simple Injector will dispose the ReaderImpl<User> at the end of the web request.
When you need to return IReader<T> implementations from a factory-like method as IRepositoryProvider.Get<T>, you will have to create an implementation that wraps the Container instance. This means that the IRepositoryProvider implementation does the following:
container.GetInstance<IReader<User>>());
In other words, this is exactly the code you described.
But be warned, prevent having any application code from taking a dependency on the Container. That's an commonly known anti-pattern called Service Locator. Instead, move the IRepositoryProvider implementation into your Composition Root.
This is a small question, just to make sure I'm understanding Unity correctly.
I'm using Unity in an ASP.NET MVC application, and I have registered a type as follows:
container.RegisterType<IPizzaService, PizzaService>();
And I'm using it in a controller like:
public class PizzaController : Controller
{
private IPizzaService _pizzaService;
public PizzaController(IPizzaService pizzaService)
{
_pizzaService = pizzaService;
}
[HttpGet]
public ActionResult Index()
{
var pizzasModel = _pizzaService.FindAllPizzas();
...
}
}
Every time a page request is done, a new instance of IPizzaService is injected and used. So this all works fine.
My question: do I have to do anything special to dispose this instance? I assume that, once the request has ended, the controller is disposed and the PizzaService instance eventually gets garbage collected.
If I need deterministic disposal of an instance because it uses an entity framework context or an unmanaged resource for example, I have to override Dispose of the controller, and there make sure I call the dispose of the instances myself.
Right? If not, please explain why :)
Thanks!
IMO, whatever creates a disposable object is responsible for disposing it. When the container injects a disposable object via RegisterType<I, T>(), I want to guarantee that the object is ready to be used. However, using RegisterInstance<I>(obj) does dispose of your object automatically.
This can be difficult with an IOC container, and is impossible with Unity out of the box. However, there is some really nifty code out there that I use all the time:
http://thorarin.net/blog/post/2013/02/12/Unity-IoC-lifetime-management-IDisposable-part1.aspx
The blog has code for a DisposingTransientLifetimeManager and DisposingSharedLifetimeManager. Using the extensions, the container calls Dispose() on your disposable objects.
One caveat is that you'll need to reference the proper (older) version of Microsoft.Practices.Unity.Configuration.dll & Microsoft.Practices.Unity.dll.
ContainerControlledTransientManager was added in Unity on Jan 11, 2018
Add container 'owned' transient lifetime manager ContainerControlledTransientManager #37
So, ContainerControlledTransientManager is required. This lifetime manager is the same as TransientLifetimeManager except if the object implements IDisposable it will keep strong reference to object and dispose it when container is disposed.
If created object is not disposable, container does not maintain any object references so when that object is released GC will collect it immediately.
I know that similar question was asked several times (for example: here, here,here and here) but it was for previous versions of Unity where the answer was dependent on used LifetimeManager class.
Documentation says:
Unity uses specific types that inherit
from the LifetimeManager base class
(collectively referred to as lifetime
managers) to control how it stores
references to object instances and how
the container disposes of these
instances.
Ok, sounds good so I decided to check implementation of build in lifetime managers. My conclusion:
TransientLifetimeManager - no handling of disposing. Container only resolves instance and it does not track it. Calling code is responsible for disposing instance.
ContainerControlledLifetimeManager - disposes instance when lifetime manager is disposed (= when container is disposed). Provides singleton instance shared among all containers in hiearchy.
HierarchicalLifetimeManager - derives behavior from ContainerControlledLifetimeManager. It provides "singleton" instance per container in hiearchy (subcontainers).
ExternallyControlledLifetimeManager - no handling of disposing. Correct behavior because container is not owner of the instance.
PerResolveLifetimeManager - no handling of disposing. It is generally same as TransientLifetimeManager but it allows reusing instance for dependency injection when resolving whole object graph.
PerThreadLifetimeManager - no handling of disposing as also described in MSDN. Who is responsible for disposing?
Implementation of build-in PerThreadLifetimeManager is:
public class PerThreadLifetimeManager : LifetimeManager
{
private readonly Guid key = Guid.NewGuid();
[ThreadStatic]
private static Dictionary<Guid, object> values;
private static void EnsureValues()
{
if (values == null)
{
values = new Dictionary<Guid, object>();
}
}
public override object GetValue()
{
object result;
EnsureValues();
values.TryGetValue(this.key, out result);
return result;
}
public override void RemoveValue()
{ }
public override void SetValue(object newValue)
{
EnsureValues();
values[this.key] = newValue;
}
}
So disposing container does not dispose disposable instances created with this lifetime manager. Thread completion will also not dispose those instances. So who is responsible for releasing instances?
I tried to manually dispose resolved instance in code and I found another problem. I can't teardown the instnace. RemoveValue of lifetime manager is empty - once the instance is created it is not possible to remove it from thread static dictionary (I'm also suspicious that TearDown method does nothing). So if you call Resolve after disposing the instance you will get disposed instance. I think this can be quite big problem when using this lifetime manager with threads from thread pool.
How to correctly use this lifetime manager?
Moreover this implementation is often reused in custom lifetime managers like PerCallContext, PerHttpRequest, PerAspNetSession, PerWcfCall, etc. Only thread static dictionary is replaced with some other construct.
Also do I understand it correctly that handling disposable objects is dependent on lifetime manager? So the application code is dependent on used lifetime manager.
I read that in other IoC containers dealing with temporary disposable objects is handled by subcontainers but I didn't find example for Unity - it could be probably handled with local scoped subcontainer and HiearchicalLifetimeManager but I'm not sure how to do it.
There are only a few circumstances where Unity will dispose an instance. It is really unsupported. My solution was a custom extension to achieve this - http://www.neovolve.com/2010/06/18/unity-extension-for-disposing-build-trees-on-teardown/
Looking at the Unity 2.0 source code, it smells like the LifetimeManagers are used to keep objects in scope in different ways so the garbage collector doesn't get rid of them. For example, with the PerThreadLifetimeManager, it will use the ThreadStatic to hold a reference on each object with that particular thread's lifetime. However, it won't call Dispose until the container is Disposed.
There is a LifetimeContainer object that is used to hold onto all the instances that are created, then is Disposed when the UnityContainer is Disposed (which, in turn, Disposes all the IDisposables in there in reverse chronological order).
EDIT: upon closer inspection, the LifetimeContainer only contains LifetimeManagers (hence the name "Lifetime"Container). So when it is Disposed, it only disposes the lifetime managers. (and we face the problem that is discussed already).
I came across this issue recently myself as I was instrumenting Unity into my application. The solutions I found here on Stack Overflow and elsewhere online didn't seem to address the issue in a satisfactory way, in my opinion.
When not using Unity, IDisposable instances have a well-understood usage pattern:
Within a scope smaller than a function, put them in a using block to get disposal "for free".
When created for an instance member of a class, implement IDisposable in the class and put clean-up in Dispose().
When passed into a class's constructor, do nothing as the IDisposable instance is owned somewhere else.
Unity confuses things because when dependency injection is done properly, case #2 above goes away. All dependencies should be injected, which means essentially no classes will have ownership of the IDisposable instances being created. However, neither does it provide a way to "get at" the IDisposables that were created during a Resolve() call, so it seems that using blocks can't be used. What option is left?
My conclusion is that the Resolve() interface is essentially wrong. Returning only the requested type and leaking objects that need special handling like IDisposable can't be correct.
In response, I wrote the IDisposableTrackingExtension extension for Unity, which tracks IDisposable instances created during a type resolution, and returns a disposable wrapper object containing an instance of the requested type and all of the IDisposable dependencies from the object graph.
With this extension, type resolution looks like this (shown here using a factory, as your business classes should never take IUnityContainer as a
dependency):
public class SomeTypeFactory
{
// ... take IUnityContainer as a dependency and save it
IDependencyDisposer< SomeType > Create()
{
return this.unity.ResolveForDisposal< SomeType >();
}
}
public class BusinessClass
{
// ... take SomeTypeFactory as a dependency and save it
public void AfunctionThatCreatesSomeTypeDynamically()
{
using ( var wrapper = this.someTypeFactory.Create() )
{
SomeType subject = wrapper.Subject;
// ... do stuff
}
}
}
This reconciles IDisposable usage patterns #1 and #3 from above. Normal classes use dependency injection; they don't own injected IDisposables, so they don't dispose of them. Classes that perform type resolution (through factories) because they need dynamically created objects, those classes are the owners, and this extension provides the facility for managing disposal scopes.
would it be a viable solution to use the HttpContext.Current.ApplicationInstance.EndRequest event to hook to the end of the request and then disposing of the object stored in this lifetime manager? like so:
public HttpContextLifetimeManager()
{
HttpContext.Current.ApplicationInstance.EndRequest += (sender, e) => {
Dispose();
};
}
public override void RemoveValue()
{
var value = GetValue();
IDisposable disposableValue = value as IDisposable;
if (disposableValue != null) {
disposableValue.Dispose();
}
HttpContext.Current.Items.Remove(ItemName);
}
public void Dispose()
{
RemoveValue();
}
you don't have to use a child container like the other solution and the code used to dispose the objects is still in the lifetime manager like it should.