I'm using delegate Factories in my application. Thats because the components I create with AutoFac use Service classes that need some Parameter.
The next Thing I wanted to do is caring that these services are cleaned up correctly and resources are released using AutoFacs lifetime scope mechanism. The Problem however is that when I create the components using the delegate factories they seem not to be put into the lifetime scope and Dispose is not called after disposing the lifetime scope.
I want to avoid the generic Owned<> because I dont want to bind my application to a specific IOC.
In http://nblumhardt.com/2011/01/an-autofac-lifetime-primer/ it is explained that the created components by a delegate factory are put into the same lifetime scope as the delegate factory.
I wrote a small Programm to demonstrate this. In this Program I would expect that the Dispose function is called. Unfortunatley this doesnt happen. Do I miss here sth? Anything wrong with the code below? How can I assure that components produced by the delegate factory are put into the life time scope of the delegate factory?
using Autofac;
using Autofac.Core;
using System;
namespace FactoryTest
{
class Component : IDisposable
{
public Component(int i) { }
public void Dispose()
{
throw new NotImplementedException();
}
}
class Program
{
static void Main(string[] args)
{
var builder = new ContainerBuilder();
builder.Register<Func<int, Component>>(c => (x) =>
{
// code that is important and that should run
// inside the delegate factory.
return new Component(x);
});
IContainer root = builder.Build();
using (ILifetimeScope lf = root.BeginLifetimeScope())
{
Func<int, Component> compDelegatefac = lf.Resolve<Func<int, Component>>();
Component cmp = compDelegatefac(2);
}
}
}
}
Edit: If you don't want to use Auto Generated Factories you can follow Delegate Factories
namespace FactoryTest
{
class Component : IDisposable
{
public delegate Component Factory(int i);
public Component(int i) { Console.WriteLine(i); }
public void Dispose()
{
Console.WriteLine("Component disposed");
}
}
class Program
{
static void Main(string[] args)
{
var builder = new ContainerBuilder();
builder.RegisterType<Component>().AsSelf();
IContainer root = builder.Build();
using (ILifetimeScope lf = root.BeginLifetimeScope())
{
var compDelegatefac = lf.Resolve<Component.Factory>();
Component cmp = compDelegatefac(2);
}
GC.Collect();
Console.Read();
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With