Skip to content

Instantly share code, notes, and snippets.

@cjjohansen
Last active April 5, 2020 19:43
Show Gist options
  • Save cjjohansen/fc7ea973391952929fc39eace1e923fa to your computer and use it in GitHub Desktop.
Save cjjohansen/fc7ea973391952929fc39eace1e923fa to your computer and use it in GitHub Desktop.
code example
using Autofac;
using MediatR;
using Microsoft.Owin;
using System.Diagnostics;
using System.Threading.Tasks;
namespace SB.PortAdapter.MediatR
{
/// <summary>
/// Wraps inner Command Handler in Autofac Lifetime scope named LifeTimeScopeKeys.PerHandlerKey
/// </summary>
/// <typeparam name="TRequest"></typeparam>
/// <typeparam name="TResponse"></typeparam>
public class LifetimeScopeCommandHandlerDecorator<TRequest, TResponse> :
IAsyncRequestHandler<TRequest, TResponse> where TRequest : class, IAsyncRequest<TResponse>
{
private readonly ILifetimeScope _scope;
/// <summary>
/// Const Name of Scope that dependencies can Match using PerMatchingLifeTimeScope(LifetimeScopeCommandHandlerDecorator.ScopeName)
/// </summary>
public const string ScopeName = LifeTimeScopeKeys.PerHandlerKey;
/// <summary>
/// constructor
/// </summary>
/// <param name="scope"></param>
public LifetimeScopeCommandHandlerDecorator(/* IOwinContext context */ ILifetimeScope scope )
{
//_owinContext = context;
_scope = scope;
}
public async Task<TResponse> Handle( TRequest request )
{
var owinContext = _scope.Resolve<IOwinContext>();
Debug.WriteLine( owinContext.GetType().FullName );
TResponse response;
using ( var perHandlerScope = _scope.BeginLifetimeScope( LifeTimeScopeKeys.PerHandlerKey ) )
{
var decoratedHandler =
perHandlerScope.ResolveKeyed<IAsyncRequestHandler<TRequest, TResponse>>( "IAsyncRequestHandlerKey" );
response = await decoratedHandler.Handle( request );
}
return response;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment