You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
//注意 AutoDecor和AutoDecorFor是想反的标注,一个标注于需要装饰的类型上,一个标注于装饰器上//标注于需要装饰的类型上//netstandard2.0 +[AutoDecor(Typeimplement)]//C#11(NET7+) support generic attribute[AutoDecor<T>]//标注于装饰器上//netstandard2.0 +[AutoDecorFor(TypeforType)]//C#11(NET7+) support generic attribute[AutoDecorFor<T>]
Define Base Service (IService or Class) & mark [AutoDecor]
请注意,如需要避免代码侵入,可以使用partial拆分业务代码和特性
[AutoDecor(typeof(HelloServiceDecor1))][AutoDecor<HelloServiceDecor2>]publicpartialinterfaceIHelloService{stringSayHello(stringname);}publicclassHelloService:IHelloService{publicstringSayHello(stringname){return$"Hello {name}";}}/// <summary>/// ClassService/// </summary>[AutoDecor<ClassServiceDecor>]publicpartialclassClassService{/// <summary>/// 请注意,如果TService是一个类,而不是interface,这里的virtual关键字是必须的/// </summary>/// <param name="name"></param>/// <returns></returns>publicvirtualstringSayHello(stringname){return$"Hello {name}";}}publicclassClassServiceDecor:ClassService{privatereadonlyClassService_helloService;privatereadonlyILogger<ClassServiceDecor>_logger;publicClassServiceDecor(ClassServicehelloService,ILogger<ClassServiceDecor>logger){_helloService=helloService;_logger=logger;}publicoverridestringSayHello(stringname){Console.WriteLine($"Hello {name} from ClassServiceDecor");varresult=_helloService.SayHello(name);_logger.LogInformation($"Hello {result} from ClassServiceDecor");returnresult;}}/// <summary>/// decor IHelloService/// </summary>publicclassHelloServiceDecor1:HelloService{privatereadonlyHelloService_helloService;publicHelloServiceDecor1(HelloServicehelloService){_helloService=helloService;}publicnewstringSayHello(stringname){Console.WriteLine($"Hello {name} from HelloServiceDecor1");return_helloService.SayHello(name);}}/// <summary>/// decor IHelloService 2/// </summary>publicclassHelloServiceDecor2:IHelloService{privatereadonlyIHelloService_helloService;publicHelloServiceDecor2(IHelloServicehelloService){_helloService=helloService;}publicstringSayHello(stringname){Console.WriteLine($"Hello {name} from HelloServiceDecor2");return_helloService.SayHello(name);}}
// add servicesbuilder.Services.AddScoped<IHelloService,HelloService>();builder.Services.AddScoped<ClassService>();// add auto decorbuilder.Services.AddAutoDecor();// get servicevarhelloService=builder.Services.GetRequiredService<IHelloService>();varclassService=builder.Services.GetRequiredService<ClassService>();