Created
April 23, 2018 14:49
-
-
Save justmara/2851b2b81150902741213bb1e9e04a2b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
siloBuilder.AddIncomingGrainCallFilter<NotFoundOperationResultInterceptor>(); | |
[NotFoundIfNotExists(nameof(CreateOrUpdate))] | |
public class MyGrain : Grain<MyState>, IMyGrain | |
{ | |
public Task<OperationResult> CreateOrUpdate(MyData data) | |
{ | |
} | |
} | |
[AttributeUsage(AttributeTargets.Class, Inherited = false)] | |
public sealed class NotFoundIfNotExistsAttribute : Attribute | |
{ | |
public NotFoundIfNotExistsAttribute(params string[] ignoreMethods) => | |
IgnoreMethods = new HashSet<string>(ignoreMethods); | |
public HashSet<string> IgnoreMethods { get; set; } | |
} | |
public class NotFoundOperationResultInterceptor : IIncomingGrainCallFilter | |
{ | |
public async Task Invoke(IIncomingGrainCallContext context) | |
{ | |
if (context.Grain is IExistableState grain) | |
{ | |
var type = context.Grain.GetType(); | |
var attr = type.GetCustomAttribute<NotFoundIfNotExistsAttribute>(); | |
if (attr != null && !attr.IgnoreMethods.Contains(context.InterfaceMethod.Name)) | |
{ | |
if (!await grain.StateExists()) | |
{ | |
var argArray = context.InterfaceMethod.ReturnType.GetGenericArguments(); | |
var opType = argArray.Any() ? argArray[0] : typeof(object); | |
if (Activator.CreateInstance(opType) is OperationResult opResult) | |
{ | |
opResult.Error = new NotFoundError<Guid> | |
{ | |
Id = context.Grain.KeyToString(), | |
Type = type.Name | |
}; | |
context.Result = opResult; | |
return; | |
} | |
} | |
} | |
} | |
await context.Invoke(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment