Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Delegate factory example for Autofac. Shows an ordinary factory and a factory returning owned instances.
namespace Demo
{
public class Application
{
private readonly IContainer container;
public Application()
{
ContainerBuilder builder = new ContainerBuilder();
builder.RegisterType<Biscuit>().As<IDependency>().Named<IDependency>("biscuits");
builder.RegisterType<Beans>().As<IDependency>().Named<IDependency>("beans");
builder.RegisterType<Worker>().As<IDisposableDependency>().Named<IDisposableDependency>("owned");
// Ordinary delegate factory.
builder.Register<Func<String, IDependency>>(delegate(IComponentContext context)
{
IComponentContext cc = context.Resolve<IComponentContext>();
return cc.ResolveNamed<IDependency>;
});
// Delegate factory that returns an 'owned' instance. This allows the component to be disposed.
builder.Register<Func<String, Owned<IDisposableDependency>>>(delegate(IComponentContext context)
{
IComponentContext cc = context.Resolve<IComponentContext>();
return cc.ResolveNamed<Owned<IDisposableDependency>>;
}).Named<Func<String, Owned<IDisposableDependency>>>("disposable-factory");
container = builder.Build();
}
/// <summary>
///
/// </summary>
public void OrdinaryWork()
{
Func<String, IDependency> factory = container.Resolve<Func<String, IDependency>>();
IDependency biscuits = factory("biscuits");
Console.Error.WriteLine(biscuits.Message());
IDependency beans = factory("beans");
Console.Error.WriteLine(beans.Message());
}
/// <summary>
///
/// </summary>
public void DisposableWork()
{
Func<String, Owned<IDisposableDependency>> factory = container.ResolveNamed<Func<String, Owned<IDisposableDependency>>>("disposable-factory");
using (Owned<IDisposableDependency> item = factory("owned"))
{
Console.Error.WriteLine(item.Value.Message());
}
}
}
}
namespace DelegateFactory
{
public class Beans : IDependency
{
public string Message()
{
return "Beans For Everyone!";
}
}
public class Biscuit : IDependency
{
public string Message()
{
return "Biscuits for all!";
}
}
public class Worker : IDisposableDependency
{
public String Message()
{
return "Disposable thingy!";
}
public void Dispose()
{
// Disposed!
Console.Error.WriteLine("I am disposed");
}
}
}
namespace Demo
{
public interface IDependency
{
String Message();
}
public interface IDisposableDependency : IDependency, IDisposable
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.