Advertisement
butoff

Minedraft_DependencyInjection

Apr 20th, 2018
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.61 KB | None | 0 0
  1.  
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Reflection;
  6.  
  7. public class CommandInterpreter : ICommandInterpreter
  8. {
  9.     private IServiceProvider serviceProvider;
  10.  
  11.     public CommandInterpreter(IServiceProvider serviceProvider)
  12.     {
  13.         this.serviceProvider = serviceProvider;
  14.     }    
  15.  
  16.  
  17.     public ICommand ProcessCommand(IList<string> args)
  18.     {
  19.         string commandName = args[0] + Constants.Command;
  20.  
  21.         List<string> data = args.Skip(1).ToList();
  22.  
  23.         Assembly assembly = Assembly.GetExecutingAssembly();
  24.  
  25.         Type commandType = assembly.GetTypes()
  26.             .FirstOrDefault(t => t.Name.Equals(commandName, StringComparison.OrdinalIgnoreCase));
  27.  
  28.         if (commandType == null)
  29.         {
  30.             throw new ArgumentException(Constants.InvalidCommand);
  31.         }
  32.  
  33.         if (!typeof(ICommand).IsAssignableFrom(commandType))
  34.         {
  35.             throw new InvalidOperationException(Constants.InvalidCommand);
  36.         }
  37.  
  38.         PropertyInfo[] propToInject = commandType.GetProperties(BindingFlags.Instance | BindingFlags.Public)
  39.                                     .Where(p => p.CustomAttributes.Any(ca => ca.AttributeType == typeof(InjectAttribute)))
  40.                                     .ToArray();
  41.  
  42.         object[] injectedArgs = propToInject.Select(p => this.serviceProvider.GetService(p.PropertyType)).ToArray();
  43.  
  44.         object[] arguments = new object[] { data }.Concat(injectedArgs).ToArray();
  45.  
  46.         ICommand command = (ICommand)Activator.CreateInstance(commandType, arguments);      
  47.  
  48.         return command;
  49.     }
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement