Advertisement
Guest User

Untitled

a guest
Dec 9th, 2019
205
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. namespace FashionNova.Web.Infrastructure
  2. {
  3. using System.Linq;
  4.  
  5. using Fashionista.Application;
  6. using FashionNova.Services.Common;
  7. using FluentValidation.AspNetCore;
  8. using Microsoft.AspNetCore.Mvc;
  9. using Microsoft.Extensions.DependencyInjection;
  10.  
  11. public static class ServiceCollectionExtensions
  12. {
  13. public static IServiceCollection AddConventionalService(
  14. this IServiceCollection services)
  15. {
  16. var serviceInterfaceType = typeof(IService);
  17. var singletonServiceInterfaceType = typeof(ISingletonService);
  18. var scopedServiceInterfaceType = typeof(IScopedService);
  19.  
  20. var types = serviceInterfaceType
  21. .Assembly
  22. .GetExportedTypes()
  23. .Where(s => s.IsClass && !s.IsAbstract)
  24. .Select(s => new
  25. {
  26. Service = s.GetInterface($"I{s.Name}"),
  27. Implementation = s,
  28. })
  29. .Where(s => s.Service != null);
  30.  
  31. foreach (var type in types)
  32. {
  33. if (serviceInterfaceType.IsAssignableFrom(type.Service))
  34. {
  35. services.AddTransient(type.Service, type.Implementation);
  36. }
  37. else if (singletonServiceInterfaceType.IsAssignableFrom(type.Service))
  38. {
  39. services.AddSingleton(type.Service, type.Implementation);
  40. }
  41. else if (scopedServiceInterfaceType.IsAssignableFrom(type.Service))
  42. {
  43. services.AddScoped(type.Service, type.Implementation);
  44. }
  45. }
  46.  
  47. return services;
  48. }
  49. }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement