Created
April 2, 2017 12:47
-
-
Save james-world/571c11b64f28baa6e27a44b818787ac3 to your computer and use it in GitHub Desktop.
Demostrates unexpected decorator behaviour in Auto 4.4.0
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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