Skip to content

Instantly share code, notes, and snippets.

@justmara
Created April 23, 2018 14:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save justmara/2851b2b81150902741213bb1e9e04a2b to your computer and use it in GitHub Desktop.
Save justmara/2851b2b81150902741213bb1e9e04a2b to your computer and use it in GitHub Desktop.
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