VContainer icon indicating copy to clipboard operation
VContainer copied to clipboard

Feature request: Object Graph Validation

Open Razenpok opened this issue 3 years ago • 3 comments

Zenject has this neat feature, would be useful to have one here

https://github.com/modesttree/Zenject#object-graph-validation

Razenpok avatar Apr 22 '22 13:04 Razenpok

I think it doesn't even matter how it's implemented - like in Zenject, or just Container.Validate() which we would need to call ourselves and which throws an Exception. Just having this feature is a huge QoL improvement.

Razenpok avatar Apr 22 '22 13:04 Razenpok

I'm currently using this IContainerBuilder wrapper for this task

using System;
using System.Collections.Generic;
using VContainer;

namespace App
{
    public class ContainerValidator : IContainerBuilder
    {
        private readonly IContainerBuilder _nested;
        private readonly List<RegistrationBuilder> _builders = new List<RegistrationBuilder>();

        public ContainerValidator(IContainerBuilder nested) => _nested = nested;

        public T Register<T>(T registrationBuilder) where T : RegistrationBuilder
        {
            _builders.Add(registrationBuilder);
            return _nested.Register(registrationBuilder);
        }

        public void RegisterBuildCallback(Action<IObjectResolver> container)
        {
            _nested.RegisterBuildCallback(container);
        }

        public bool Exists(Type type, bool includeInterfaceTypes = false)
        {
            return _nested.Exists(type, includeInterfaceTypes);
        }

        public object ApplicationOrigin
        {
            get => _nested.ApplicationOrigin;
            set => _nested.ApplicationOrigin = value;
        }

        public void Validate(IObjectResolver resolver)
        {
            foreach (var builder in _builders)
            {
                var registration = builder.Build();

                if (registration.InterfaceTypes != null)
                {
                    foreach (var interfaceType in registration.InterfaceTypes)
                    {
                        resolver.Resolve(interfaceType);
                    }
                }
                else
                {
                    resolver.Resolve(registration.ImplementationType);
                }
            }
        }
    }
}

Razenpok avatar Apr 22 '22 14:04 Razenpok

thus, dependency graph would be nice to have too then! but it's not that much important as validation, I agree

cherrynik avatar May 17 '23 22:05 cherrynik