Skip to content

Instantly share code, notes, and snippets.

@danielplawgo
Created March 9, 2021 19: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 danielplawgo/9b0d2239136fbe7d0afd8f13a8a8e8ed to your computer and use it in GitHub Desktop.
Save danielplawgo/9b0d2239136fbe7d0afd8f13a8a8e8ed to your computer and use it in GitHub Desktop.
Scrutor użycie dekoratora
public class DecoratorAttribute : Attribute
{
}
public interface IProductRepository : IRepository
{
Product GetById(Guid id);
}
public class ProductRepository : IProductRepository
{
public Product GetById(Guid id)
{
return new Product()
{
Id = id
};
}
}
public class ProductRepositoryLoggerDecorator : IProductRepository
{
private readonly IProductRepository _productRepository;
private readonly ILogger<ProductRepositoryLoggerDecorator> _logger;
public ProductRepositoryLoggerDecorator(IProductRepository productRepository, ILogger<ProductRepositoryLoggerDecorator> logger)
{
_productRepository = productRepository;
_logger = logger;
}
public Product GetById(Guid id)
{
var repositoryType = _productRepository.GetType();
_logger.LogInformation($"Executing {repositoryType.Namespace} GetById - id: {id}");
var product = _productRepository.GetById(id);
_logger.LogInformation($"Executed {repositoryType.Namespace} GetById - id: {id}");
return product;
}
}
[Decorator]
public class ProductRepositoryLoggerDecorator : IProductRepository
{
....
}
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddRepositories(this IServiceCollection services)
{
services.AddScoped<IProductRepository, ProductRepository>();
services.TryDecorate<IProductRepository, ProductRepositoryLoggerDecorator>();
return services;
}
}
public static class ServiceCollectionExtensions
{
public static IServiceCollection AddRepositories(this IServiceCollection services)
{
services.Scan(s => s.FromAssemblyOf<IRepository>()
.AddClasses(c => c.AssignableTo<IRepository>().WithoutAttribute<DecoratorAttribute>())
.AsImplementedInterfaces()
.WithScopedLifetime());
services.TryDecorate<IProductRepository, ProductRepositoryLoggerDecorator>();
return services;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment