Created
April 5, 2020 19:53
-
-
Save cjjohansen/acf94863e62e4f8745bc36728345f11e to your computer and use it in GitHub Desktop.
Autofac LifeTimeScopeDecorator
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
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