Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public IExecutable InterpretCommand(string[] data, string commandName)
- {
- // взимаме всички типове в програмата това е пример за command pattern
- Assembly assembly = Assembly.GetCallingAssembly();
- Type commandType = assembly.GetTypes()
- .FirstOrDefault(t => t.Name.ToLower() == commandName + "command");
- //2 проверки дали съществува и дали абстракния интерфейс е наследствен в командата
- if (commandType == null)
- {
- throw new ArgumentException("Invalid command!");
- }
- if (!typeof(IExecutable).IsAssignableFrom(commandType))
- {
- throw new ArgumentException("invalid command!");
- }
- //обхождаме полетата на класа които се подават през конструктора,тук ползваме dependency injection
- FieldInfo[] fieldsToInject = commandType.GetFields(BindingFlags.NonPublic | BindingFlags.Instance)
- .Where(f => f.CustomAttributes.Any(ca => ca.AttributeType == typeof(InjectAttribute))).ToArray();
- //activatora ползва оbject array затова създаваме array oт нужните ни обекти
- object[] injectArgs = fieldsToInject.Select(f => this.serviceProvider.GetService(f.FieldType)).ToArray();
- object [] constArgs=new object[]{data}.Concat(injectArgs).ToArray();
- // създавме командата като пак я кастваме към интерфейса
- IExecutable command = (IExecutable)Activator.CreateInstance(commandType, constArgs);
- // връщаме командата.
- return command;
- }
Advertisement
Add Comment
Please, Sign In to add comment