This is similar to how my code looks
var catalog = new AssemblyCatalog(typeof(Program).Assembly);
_container = new CompositionContainer(catalog);
Code Analysis is showing a warning CA2000: call Dispose on catalog before all references to it are out of scope.
So I'm not sure if I need to suppress the warning or turn _catalog into a field + Dispose it.
The MEF Docs don't seem to mention this.
According to the MEF Preview 9 source code (which probably closely matches the code that shipped in .NET 4) CompositionContainer will wrap the catalog in a CatalogExportProvider. This export provider is stored in a field and disposed along with the container. However, CatalogExportProvider.Dispose will not in turn dispose the wrapped ComposablePartCatalog.
Therefore the answer is no: CompositionContainer does not dispose the catalog.
You can verify this by running this code, which will not print anything to the console:
class MyCatalog : ComposablePartCatalog
{
protected override void Dispose(bool disposing)
{
Console.WriteLine("Disposed!");
base.Dispose();
}
public override IQueryable<ComposablePartDefinition> Parts
{
get { throw new NotImplementedException(); }
}
}
class Program
{
static void Main(string[] args)
{
var container = new CompositionContainer(new MyCatalog());
container.Dispose();
Console.ReadKey();
}
}
As Wim already discovered neither the CompsitionContainer nor the CatalogExportProvider will call dispose on the catalog. Neither of them created the catalog thus neither of them own it and as such will not call Dispose on it. Whoever constructs the catalog should be the one that disposes it.
There are a lot of scenarios where someone would want to share a catalog instance with multiple containers which is why the container doesn't have ownership of the catlaog and therefore doesn't dispose it.
Related
The idea is just simple and works in the other containers, not limited with .Net:
Singleton component being referenced from within request context references transient component which in turn references request-scoped component (some UnitOfWork).
I expected that Autofac would resolve the same scoped component in both cases:
- when I request it directly from request scope
- when I request it by invoking Func<>
Unfortunately the reality is quite a bit different - Autofac sticks SingleInstance component to the root scope and resolves InstancePerLifetimeScope component on
the root component introducing memory leak (!!!) as UnitOfWork is disposable and becomes tracked by root scope (attempt to use matching web request scope would just fail finding request scope which is yet more misleading).
Now I'm wondering whether such behavior is by design or just a bug? If it is by design I'm not sure what are the use cases and why it differs from the other containers.
The example is as follows (including working SimpleInjector case):
namespace AutofacTest
{
using System;
using System.Linq;
using System.Linq.Expressions;
using Autofac;
using NUnit.Framework;
using SimpleInjector;
using SimpleInjector.Lifestyles;
public class SingletonComponent
{
public Func<TransientComponent> Transient { get; }
public Func<ScopedComponent> Scoped { get; }
public SingletonComponent(Func<TransientComponent> transient, Func<ScopedComponent> scoped)
{
Transient = transient;
Scoped = scoped;
}
}
public class ScopedComponent : IDisposable
{
public void Dispose()
{
}
}
public class TransientComponent
{
public ScopedComponent Scoped { get; }
public TransientComponent(ScopedComponent scopedComponent)
{
this.Scoped = scopedComponent;
}
}
class Program
{
static void Main(string[] args)
{
try
{
AutofacTest();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
try
{
SimpleInjectorTest();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private static void AutofacTest()
{
var builder = new ContainerBuilder();
builder.RegisterType<ScopedComponent>().InstancePerLifetimeScope();
builder.RegisterType<SingletonComponent>().SingleInstance();
builder.RegisterType<TransientComponent>();
var container = builder.Build();
var outerSingleton = container.Resolve<SingletonComponent>();
using (var scope = container.BeginLifetimeScope())
{
var singleton = scope.Resolve<SingletonComponent>();
Assert.That(outerSingleton, Is.SameAs(singleton));
var transient = scope.Resolve<TransientComponent>();
var scoped = scope.Resolve<ScopedComponent>();
Assert.That(singleton.Transient(), Is.Not.SameAs(transient));
// this fails
Assert.That(singleton.Transient().Scoped, Is.SameAs(scoped));
Assert.That(transient.Scoped, Is.SameAs(scoped));
Assert.That(singleton.Scoped(), Is.SameAs(scoped)); // this fails
Assert.That(singleton.Transient(), Is.Not.SameAs(transient));
}
}
private static void SimpleInjectorTest()
{
var container = new SimpleInjector.Container();
container.Options.AllowResolvingFuncFactories();
container.Options.DefaultScopedLifestyle = new AsyncScopedLifestyle();
container.Register<ScopedComponent>(Lifestyle.Scoped);
container.Register<SingletonComponent>(Lifestyle.Singleton);
container.Register<TransientComponent>(Lifestyle.Transient);
container.Verify();
var outerSingleton = container.GetInstance<SingletonComponent>();
using (var scope = AsyncScopedLifestyle.BeginScope(container))
{
var singleton = container.GetInstance<SingletonComponent>();
Assert.That(outerSingleton, Is.SameAs(singleton));
var transient = container.GetInstance<TransientComponent>();
var scoped = container.GetInstance<ScopedComponent>();
Assert.That(singleton.Transient(), Is.Not.SameAs(transient));
Assert.That(singleton.Transient().Scoped, Is.SameAs(scoped));
Assert.That(transient.Scoped, Is.SameAs(scoped));
Assert.That(singleton.Scoped(), Is.SameAs(scoped));
Assert.That(singleton.Transient(), Is.Not.SameAs(transient));
}
}
}
public static class SimpleInjectorExtensions
{
public static void AllowResolvingFuncFactories(this ContainerOptions options)
{
options.Container.ResolveUnregisteredType += (s, e) =>
{
var type = e.UnregisteredServiceType;
if (!type.IsGenericType || type.GetGenericTypeDefinition() != typeof(Func<>))
{
return;
}
Type serviceType = type.GetGenericArguments().First();
InstanceProducer registration = options.Container.GetRegistration(serviceType, true);
Type funcType = typeof(Func<>).MakeGenericType(serviceType);
var factoryDelegate = Expression.Lambda(funcType, registration.BuildExpression()).Compile();
e.Register(Expression.Constant(factoryDelegate));
};
}
}
}
The short version what you're seeing is not a bug, you're just misunderstanding some of the finer points of lifetime scopes and captive dependencies.
First, a couple of background references from the Autofac docs:
Controlling Scope and Lifetime explains a lot about how lifetime scopes and that hierarchy works.
Captive Dependencies talks about why you don't generally shouldn't take an instance-per-lifetime or instance-per-dependency scoped item into a singleton.
Disposal talks about how Autofac auto-disposes IDisposable items and how you can opt out of that.
Implicit Relationship Types describes the Owned<T> relationship type used as part of the IDisposable opt-out.
Some big key takeaways from these docs that directly affect your situation:
Autofac tracks IDisposable components so they can be automatically disposed along with the lifetime scope. That means it will hold references to any resolved IDisposable objects until the parent lifetime scope is resolved.
You can opt out of IDisposable tracking either by registering the component as ExternallyOwned or by using Owned<T> in the constructor parameter being injected. (Instead of taking in an IDependency take in an Owned<IDependency>.)
Singletons live in the root lifetime scope. That means any time you resolve a singleton it will be resolved from the root lifetime scope. If it is IDisposable it will be tracked in the root lifetime scope and not released until that root scope - the container itself - is disposed.
The Func<T> dependency relationship is tied to the same lifetime scope as the object in which it's injected. If you have a singleton, that means the Func<T> will resolve things from the same lifetime scope as the singleton - the root lifetime scope. If you have something that's instance-per-dependency, the Func<T> will be attached to whatever scope the owning component is in.
Knowing that, you can see why your singleton, which takes in a Func<T>, keeps trying to resolve these things from the root lifetime scope. You can also see why you're seeing a memory leak situation - you haven't opted out of the disposal tracking for the things that are being resolved by that Func<T>.
So the question is, how do you fix it?
Option 1: Redesign
Generally speaking, it would be better to invert the relationship between the singleton and the thing you have to resolve via Func<T>; or stop using a singleton altogether and let that be a smaller lifetime scope.
For example, say you have some IDatabase service that needs an IPerformTransaction to get things done. The database connection is expensive to spin up, so you might make that a singleton. You might then have something like this:
public class DatabaseThing : IDatabase
{
public DatabaseThing(Func<IPerformTransaction> factory) { ... }
public void DoWork()
{
var transaction = this.factory();
transaction.DoSomethingWithData(this.Data);
}
}
So, like, the thing that's expensive to spin up uses a Func<T> to generate the cheap thing on the fly and work with it.
Inverting that relationship would look like this:
public PerformsTransaction : IPerformTransaction
{
public PerformsTransaction(IDatabase database) { ... }
public void DoSomethingWithData()
{
this.DoSomething(this.Database.Data);
}
}
The idea is that you'd resolve the transaction thing and it'd take the singleton in as a dependency. The cheaper item could easily be disposed along with child lifetime scopes (i.e., per request) but the singleton would remain.
It'd be better to redesign if you can because even with the other options you'll have a rough time getting "instance per request" sorts of things into a singleton. (And that's a bad idea anyway from both a captive dependency and threading standpoint.)
Option 2: Abandon Singleton
If you can't redesign, a good second choice would be to make the lifetime of the singleton... not be a singleton. Let it be instance-per-scope or instance-per-dependency and stop using Func<T>. Let everything get resolved from a child lifetime scope and be disposed when the scope is disposed.
I recognize that's not always possible for a variety of reasons. But if it is possible, that's another way to escape the problem.
Option 3: Use ExternallyOwned
If you can't redesign, you could register the disposable items consumed by the singleton as ExternallyOwned.
builder.RegisterType<ThingConsumedBySingleton>()
.As<IConsumedBySingleton>()
.ExternallyOwned();
Doing that will tell Autofac to not track the disposable. You won't have the memory leak. You will be responsible for disposing the resolved objects yourself. You will also still be getting them from the root lifetime scope since the singleton is getting a Func<T> injected.
public void MethodInsideSingleton()
{
using(var thing = this.ThingFactory())
{
// Do the work you need to and dispose of the
// resolved item yourself when done.
}
}
Option 4: Owned<T>
If you don't want to always manually dispose of the service you're consuming - you only want to deal with that inside the singleton - you could register it as normal but consume a Func<Owned<T>>. Then the singleton will resolve things as expected but the container won't track it for disposal.
public void MethodInsideSingleton()
{
using(var ownedThing = this.ThingFactory())
{
var thing = ownedThing.Value;
// Do the work you need to and dispose of the
// resolved item yourself when done.
}
}
I know this question has been asked several times before, but I couldn't get the answer I was looking for.
So, I've implemented the Repository (generic) and UOW pattern, so I can access my DB using EF. Here's part of the UnitOfWork class:
protected virtual void Dispose(bool disposing)
{
if (!disposed)
{
if (disposing)
{
entities.Dispose();
}
}
this.disposed = true;
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
The question is: Who is calling the void Dispose method?? I've seen no example of the usage of that method.
this it the upper part of the Unit Of Work class:
private BDEntities entities = null;
public UnitOfWork()
{
if (entities == null)
{
entities = new BDEntities();
}
}
Is this right? should I use "Using"? and if yes, than why do I need the Dispose method?
Can you give me an example of a proper and simple usage?
Thank you,
Rotem
The reason why you have not come across any examples about who calls the dispose is because UoW is usually used together with dependency injection and a dependency injection container, like Autofac. And in this case, it is the responsibility of this container to create objects and dispose of them later. Granted, this is not the only way UoW can be used, but it is a common pattern.
As for answering your question: I think the approach that you are taking is more or less right. The UoW class should be the one that wraps the context, so it should be the one to dispose it as well (essentially, the DbContext itself is a UoW).
You can simplify the Dispose method though. Since you do not have any unmanaged and not IDisposable resources (like pointers), it is completely enough to call the Dispose method of the context in the Dispose method of the UoW:
public void Dispose()
{
entities.Dispose();
}
(No other Dispose method, no SuppressFinalize calls).
And yes, you should absolutely use using. And that's exactly why you need a the Dispose() method; only objects that are of a type that implements IDisposable can be used in a using block. If you write a using block, it basically translates to a try-finally block; your code from inside the using block goes into the try block, and in the finally, the Dispose() is called.
What is the true usage of dispose ?
This is first (my) approach:
public class RequestService : IDisposable
{
requestDBEntities db;
public RequestService() //Constructor
{
db = new requestDBEntities ();
}
public List<RequestStatus> ddlFill()
{
return (from rs in db.reqStatus select rs).ToList();
}
//Some Insert,Update,Delete methods {}...
public void Dispose()
{
db.Dispose(); //<--Dispose requestDBEntities();
GC.SuppressFinalize(this);
}
And second approach:
public class RequestService : IDisposable
{
requestDBEntities db;
public List<RequestStatus> ddlFill()
{
using (db = new requestDBEntities())
return (from rs in db.reqStatus select rs).ToList();
}
//Some Insert,Update,Delete methods {}...
public void Dispose()
{
GC.SuppressFinalize(this);
}
Page Code-behind:
using (RequestService _reqService = new RequestService ())
{
ddlRequestStatus.DataSource = _reqService.ddlFill();
ddlRequestStatus.DataBind();
//Some Insert,Update,Delete operations...
}
Thank you..
It's difficult (impossible) to say which is the better approach, since we don't know your exact design choice. From the perspective of a simple app, it may seem that the two examples are equivalent (more or less), but they really do behave in entirely different ways.
The fundamental question here is: Should the lifetime of db be comparable to the lifetime of its enclosing RequestService instance?
If yes, then the first code example is the way to do things. Resources will be managed as expected (db disposes its stuff at the same time the RequestService object is asked to dispose of its resources), and the lifetime of the two will be pretty much identical (db is constructed in the RequestService constructor, and db become collectable as soon as its RequestService object becomes collectable).
However, if the answer is "no", then the second example is (almost) the way to do things - since you generate a collection view of the RequestStatus object from db, you really have no reason to keep db around any longer. However, to make this a bit better, may I suggest restricting the scope of db to within the ddlFill method:
public List<RequestStatus> ddlFill()
{
using (var db = new requestDBEntities())
return (from rs in db.reqStatus select rs).ToList();
}
No need for an extraneous class member when a stack value suffices.
What for in second example you have declared requestDBEntities db; at class level instead of having it as a stack variable?
Comparing your approaches, the question is - are you ready to create requestDBEntities on each call? If you are - second approach is better, in fact if there is nothing else you haven'y posted - you don't need dispose at all. But you'll have extra time penalty on instantiating/releasing requestDBEntities on each call.
I have a WPF view that has a corresponding ViewModel. All instances are resolved via an unity container. Because I'm using prism I need two independent instances of the view to add it into two different regions the view is registered to. If I'd try to add one instance into both regions I get an
InvalidOperationException: Specified
element is already the logical child
of another element. Disconnect it
first.
when the view is added into the second region because it is already added to the first region.
This problem can easily be solved by using a TransientLifetimeManager that always returns a new instance so both regions would be filled with an independent instance.
But we have decided to create a child container when a new user logs on. Every session related view and view model are resolved using this child container. When the user's session ends, the child container is disposed so that also every session related instances are disposed. But using a TransientLifetimeManager the unity container cannot dispose those instances.
What we need is a lifetime manager that always returns a new instance, but is also capable of disposing those instances. Is there already such an lifetime manager around? Or is there another way to achieve what I described above?
What you want sounds like a variant of the ContainerControlledLifetime manager that does not maintain a singleton instance, but a collection of instances. Unfortunately this is not one of the built-in lifetime managers.
You can look at the code for the ContainerControlledLifetimeManager and see that it is pretty simple. Your "SynchronizedGetValue" implementation would always return null (signaling to the container that a new instance needs to be instantiated). You could just subclass ContainerControlledLifetimeManager and override that method.
I've pretty much written it. I suppose I could give you the code. :)
public class ContainerTrackedTransientLifetimeManager :
ContainerControlledLifetimeManager
{
protected override object SynchronizedGetValue()
{
return null;
}
}
That should work. I've not tested it... from the interface, it looks like it's designed for a 1 to 1 LifetimeManager to Object relationship, but if it turns out it is more than that, you might have to override SetValue (adds to a collection of objects) and dispose (disposes that collection of objects). Here's that implementation:
public class ContainerTrackedTransientLifetimeManager :
SynchronizedLifetimeManager, IDisposable
{
private ConcurrentCollection<object> values = new ConcurrentCollection<object>();
protected override object SynchronizedGetValue()
{
return null;
}
protected override void SynchronizedSetValue(object newValue)
{
values.Add(newValue);
}
public override void RemoveValue()
{
Dispose();
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
protected void Dispose(bool disposing)
{
var disposables = values.OfType<IDisposable>();
foreach(var disposable in disposables)
{
disposable.Dispose();
}
values.Clear();
}
I'm not sure which of these is the right answer. Let me know how it goes for you.
When you use transient lifetime manager (which is the default), Unity does not keep a reference to the created instance.
Thus, when there are no more reference to the instance, it will be GCed.
newbie here, sorry if this is an obvious question.
I've read from this page: http://code.google.com/p/autofac/wiki/NewInV2
In Autofac 1, weak references are held by the container. This makes sense if the objects being referenced use disposal to release GC/finalizer resources, but if the dispose method contains application logic then GC timing could introduce unexpected behaviour.
Autofac 2 holds normal references. To opt out of this behaviour and mange disposal manually, use the ExternallyOwned registration modifier.
Is that mean when I need to release an object that is resolved by Autofac to the GC, I cannot simply say:
a = null;
because Autofac holds a strong reference to the object. Instead, I should use Owned<>:
public class MyClass
{
public MyClass(Owned<A> a)
{
a.Value.Dosomething();
a.Dispose();
}
}
or use the ExternallyOwned registration modifier:
builder.RegisterAssemblyTypes(Assembly.GetExecutingAssembly()).ExternallyOwned();
later on, I should be able to use a = null to release the object to the GC.
Is that right?
Thanks!
By default, you don't need to dispose anything - Autofac will automatically identify and dispose any IDisposable instances it created when their containing lifetime scope is disposed.
You only need to use Owned<T> or ExternallyOwned() if you have a reason to manage the lifetime of the object manually. If you resolve an Owned<T> then you should call t.Dispose() yourself - the common usage pattern is to take a dependency on a factory delegate:
public class MyClass
{
private Func<Owned<User>> myDisposableFactory;
public MyClass(Func<Owned<User>> myDisposableFactory)
{
this.myDisposableFactory = myDisposableFactory;
}
public void DoSomething()
{
using (var disposable = this.myDisposableFactory())
{
// ...
disposable.Dispose();
}
}
}
If you register a type as ExternallyOwned() then Autofac will not dispose of any resolved instance when the containing lifetime scope ends - it's up to you to manage it.
Take a look at Nicholas Blumhardt's article on lifetimes for more information.