装饰者模式 在依赖注入中体现
Decorator in Dependency Injection
public interface IReportServer { void PrintReport(); } public class ReportService : IReportServer { public void PrintReport() { Console.WriteLine("Printing..."); } } public class ReportServiceWithLogging : IReportServer { private readonly IReportServer reportServer; public ReportServiceWithLogging(IReportServer reportServer) { this.reportServer = reportServer; } public void PrintReport() { Console.WriteLine("Begining."); reportServer.PrintReport(); Console.WriteLine("Ending."); } } class Program { static void Main(string[] args) { var container = new ContainerBuilder(); container.RegisterType<ReportService>().Named<IReportServer>("report"); container.RegisterDecorator<IReportServer>( (context,server)=>new ReportServiceWithLogging(server), "report" ); using (var cb=container.Build()) { var report= cb.Resolve<IReportServer>(); report.PrintReport(); } } }