Interface <T>: T
Let's say I have this structure of classes and interfaces:
interface IService {}
interface IEmailService : IService
{
Task SendAsync(IMessage message);
}
class EmailService : IEmailService
{
async Task SendAsync(IMessage message)
{
await ...
}
}
interface ICircuitBreaker<TService> : IService where TService : IService
{
TService Service { get; set; }
Task<IResult> PerformAsync(Func<Task<Iresult>> func);
}
class EmailServiceCircuitBreaker : ICircuitBreaker<IEmailService>
{
IEmailService Service { get; set; }
public EmailServiceCircuitBreaker(IEmailService service)
{
Service = service;
}
public async Task<IResult> PerformAsync(Func<Task<Iresult>> func)
{
try
{
func();
}
catch(Exception e){//Handle failure}
}
}
So now I would like to change EmailServiceCircuitBreakerto:
class EmailServiceCircuitBreaker : ICircuitBreaker<IEmailService>, IEmailService
so I can wrap each method from IEmailServiceand Send(...)will look like this:
async Task<IResult> IEmailService.SendAsync(IMessage m)
=> await PerformAsync(async () => await Service.SendAsync(m));
And in the controller I can use it as IEmailService, even if it is ICircuitBreaker<IEmailService>, without knowing it.
But, if one of my colleagues fulfills ICircuitBreaker<T>, I would like to make his class also implementT
+4
1 answer
If you do not have a new language restriction, then you can create your own compilation errors
, , DiagnosticAnalyzer
https://johnkoerner.com/csharp/creating-your-first-code-analyzer/
DiagnosticAnalyzer,
context.RegisterSymbolAction(AnalyzeSymbol, SymbolKind.NamedType);
private static void AnalyzeSymbol(SyntaxNodeAnalysisContext context)
{
var node = (ObjectCreationExpressionSyntax)context.Node;
if (node != null && node.Type != null && node.Type is IdentifierNameSyntax)
{
var type = (IdentifierNameSyntax)node.Type;
var symbol = (INamedTypeSymbol)context.SemanticModel.GetSymbolInfo(type).Symbol;
var isIService = IsInheritedFromIService(symbol);
if (isIService )
{
... //Check you logic
context.ReportDiagnostic(diagnostic);
}
}
}
private static bool IsInheritedFromIService(ITypeSymbol symbol)
{
bool isIService = false;
var lastParent = symbol;
if (lastParent != null)
{
while (lastParent.BaseType != null)
{
if (lastParent.BaseType.Name == "IService")
{
isIService = true;
lastParent = lastParent.BaseType;
break;
}
else
{
lastParent = lastParent.BaseType;
}
}
}
return isIService ;
}
+3