57 lines
		
	
	
		
			1.8 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
			
		
		
	
	
			57 lines
		
	
	
		
			1.8 KiB
		
	
	
	
		
			C#
		
	
	
	
	
	
| using System;
 | |
| using System.Reflection;
 | |
| using RebootKit.Engine.Foundation;
 | |
| 
 | |
| namespace RebootKit.Engine.Services.Console {
 | |
|     [AttributeUsage(AttributeTargets.Field)]
 | |
|     public class CVarAttribute : Attribute {
 | |
|         public CVarAttribute(string name, float defaultValue) {
 | |
|             Name = name;
 | |
|             Value = new CVarValue(defaultValue);
 | |
|         }
 | |
| 
 | |
|         public CVarAttribute(string name, double defaultValue) {
 | |
|             Name = name;
 | |
|             Value = new CVarValue(defaultValue);
 | |
|         }
 | |
| 
 | |
|         public CVarAttribute(string name, string defaultValue) {
 | |
|             Name = name;
 | |
|             Value = new CVarValue(defaultValue);
 | |
|         }
 | |
| 
 | |
|         public CVarAttribute(string name, int defaultValue) {
 | |
|             Name = name;
 | |
|             Value = new CVarValue(defaultValue);
 | |
|         }
 | |
| 
 | |
|         public string Name { get; }
 | |
|         public CVarValue Value { get; }
 | |
|     }
 | |
| 
 | |
|     public class CVarFieldInjector : DIContext.IFieldInjector {
 | |
|         static readonly Logger s_logger = new(nameof(CVarFieldInjector));
 | |
| 
 | |
|         public bool Inject(FieldInfo field, object target, DIContext context) {
 | |
|             if (!Attribute.IsDefined(field, typeof(CVarAttribute))) return false;
 | |
| 
 | |
|             ConsoleService console = context.Resolve<ConsoleService>();
 | |
|             if (console == null) {
 | |
|                 s_logger.Error($"Cannot inject field because cannot resolve `{nameof(ConsoleService)}`");
 | |
|                 return false;
 | |
|             }
 | |
| 
 | |
|             CVarAttribute cvarAttribute = field.GetCustomAttribute<CVarAttribute>();
 | |
|             CVar cvar = console.GetCVar(cvarAttribute.Name);
 | |
| 
 | |
|             if (cvar == null) {
 | |
|                 cvar = new CVar(cvarAttribute.Name, cvarAttribute.Value);
 | |
|                 console.Replace(cvar);
 | |
|             }
 | |
| 
 | |
|             field.SetValue(target, cvar);
 | |
| 
 | |
|             return true;
 | |
|         }
 | |
|     }
 | |
| } |