Skip to content

Instantly share code, notes, and snippets.

@biswanaths
Created January 12, 2012 17:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save biswanaths/1601884 to your computer and use it in GitHub Desktop.
Save biswanaths/1601884 to your computer and use it in GitHub Desktop.
Container dispose, disposes the components it has provided
using System;
using System.Globalization;
using Autofac;
namespace ConsoleApplication1
{
class Program
{
class Good:IDisposable
{
private bool _isDisposed = false;
public Good()
{
}
public void Dispose()
{
_isDisposed = true;
}
public void DoGoodThings()
{
if (_isDisposed )
Console.WriteLine(DateTime.Now.ToString(CultureInfo.InvariantCulture) + " I can no more do good thing.");
else
Console.WriteLine(DateTime.Now.ToString(CultureInfo.InvariantCulture) + " I am doing good things.");
}
}
class SomeIDisposable:IDisposable
{
public void Dispose()
{
}
}
static void Main(string[] args)
{
var builder = new ContainerBuilder();
builder.RegisterType<Good>();
Good goodNessFromAutofac;
Good ordinaryGoodNess;
using ( var container = builder.Build())
{
goodNessFromAutofac = container.Resolve<Good>();
goodNessFromAutofac.DoGoodThings();
}
// watch this thing
goodNessFromAutofac.DoGoodThings();
// all though it lets you do something
// question to ask, Should be object be used after
// dispose is called
// Think about situtations where in dispose resource and memory would have freed of
// Think about database connection
using (var someIDisposable = new SomeIDisposable())
{
ordinaryGoodNess = new Good();
ordinaryGoodNess.DoGoodThings();
}
ordinaryGoodNess.DoGoodThings();
var otherbuilder = new ContainerBuilder();
// tell autofac that I am responsible for my IDisposable
otherbuilder.RegisterType<Good>().ExternallyOwned();
using (var container = otherbuilder.Build())
{
goodNessFromAutofac = container.Resolve<Good>();
goodNessFromAutofac.DoGoodThings();
}
goodNessFromAutofac.DoGoodThings();
Console.ReadKey();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment