Skip to content

Instantly share code, notes, and snippets.

@james-world
Created April 2, 2017 12:47
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 james-world/571c11b64f28baa6e27a44b818787ac3 to your computer and use it in GitHub Desktop.
Save james-world/571c11b64f28baa6e27a44b818787ac3 to your computer and use it in GitHub Desktop.
Demostrates unexpected decorator behaviour in Auto 4.4.0
// Suitable for LINQPad with the Autofac nuget package
void Main()
{
ExpectedBehaviour();
UnexpectedBehaviour();
}
public void ExpectedBehaviour()
{
var builder = new ContainerBuilder();
builder.RegisterType<FooOne>().As<IFoo>();
// replaces default IFoo implementation
builder.RegisterType<FooTwo>().As<IFoo>();
var container = builder.Build();
Console.WriteLine(container.Resolve<IFoo>().Execute());
}
public void UnexpectedBehaviour()
{
var builder = new ContainerBuilder();
// comment next line to get working decorator
builder.RegisterType<FooOne>().As<IFoo>();
builder.RegisterType<FooOne>().Named<IFoo>("foo");
// default IFoo implementation is not replaced
builder.RegisterDecorator<IFoo>((c, inner) => new DecoratorFoo(inner), fromKey: "foo");
var container = builder.Build();
Console.WriteLine(container.Resolve<IFoo>().Execute());
}
public interface IFoo
{
string Execute();
}
// Define other methods and classes here
public class FooOne : IFoo
{
public string Execute() => "FooOne.Execute";
}
public class FooTwo : IFoo
{
public string Execute() => "FooTwo.Execute";
}
public class DecoratorFoo : IFoo
{
private IFoo inner;
public DecoratorFoo(IFoo inner)
{
this.inner = inner;
}
public string Execute() => "Decorated " + inner.Execute();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment