Ejemplo n.º 1
0
    public void InjectServices(object o, PluginContainer container, ILogger logger)
    {
        var serviceCache = new Dictionary <Type, object>();

        PropertyInfo[] properties = o.GetType().GetProperties();
        foreach (var property in properties)
        {
            if (property.GetCustomAttribute <InjectAttribute>() == null)
            {
                continue;
            }

            if (property.PropertyType.IsAssignableTo(typeof(PluginBase)))
            {
                continue;
            }

            if (serviceImplementationTypes.TryGetValue(property.PropertyType, out var implementationType))
            {
                if (!serviceCache.TryGetValue(property.PropertyType, out var service))
                {
                    service = Activator.CreateInstance(implementationType, container);
                    serviceCache.Add(property.PropertyType, service);

                    if (service is SecuredServiceBase securedService)
                    {
                        container.RegisterSecuredService(securedService);
                    }

                    if (service is IDisposable disposableService)
                    {
                        container.RegisterDisposableService(disposableService);
                    }
                }

                property.SetValue(o, service);
            }
            else if (singletons.TryGetValue(property.PropertyType, out var singleton))
            {
                property.SetValue(o, singleton);
            }
            else
            {
                logger?.LogError($"Failed injecting into {container.Info.Name}.{property.Name} property, because {property.PropertyType} is not a valid service.");
            }
        }
    }