Last active
June 26, 2019 09:35
-
-
Save horse315/a55978a4838fb401177a5a9f682a694c to your computer and use it in GitHub Desktop.
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
using Autofac; | |
using System; | |
namespace AutofacDecorator | |
{ | |
class Program | |
{ | |
/// <summary> | |
/// dotnet add package Autofac --version 4.9.2 | |
/// </summary> | |
/// <param name="args"></param> | |
static void Main(string[] args) | |
{ | |
var containerBuilder = new ContainerBuilder(); | |
// redis | |
containerBuilder.Register(c => | |
{ | |
return new WorkProvider(); | |
}).As<IWorkProvider>().SingleInstance(); | |
containerBuilder.Register(c => | |
{ | |
var x = c.Resolve<IWorkProvider>(); | |
return x.GetWork(); // replace with (Work)x.GetWork() to make it work | |
}).As<IWork>().InstancePerLifetimeScope(); | |
// decorator | |
containerBuilder.RegisterDecorator<IWork>((c, p, decorated) => new WorkDecorator(decorated)); | |
var container = containerBuilder.Build(); | |
var work = container.Resolve<IWork>(); | |
work.DoWork(); | |
} | |
} | |
public class WorkProvider : IWorkProvider | |
{ | |
public IWork GetWork() => new Work(); | |
} | |
public class Work : IWork | |
{ | |
public void DoWork() => Console.WriteLine("meow"); | |
} | |
public class WorkDecorator : IWork | |
{ | |
private IWork _decorated; | |
public WorkDecorator(IWork decorated) | |
{ | |
_decorated = decorated; | |
} | |
public void DoWork() | |
{ | |
Console.WriteLine($"Decorated DoWork"); | |
_decorated.DoWork(); | |
} | |
} | |
public interface IWorkProvider | |
{ | |
IWork GetWork(); | |
} | |
public interface IWork | |
{ | |
void DoWork(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment