DaniilSokolyuk/DS.Unity.Extensions.DependencyInjection

DependencyAttribute not supported

MistyKuu opened this issue · 3 comments

When trying to resolve class which has DependencyAttribute in constructor parameters it will not work because it will not find implementation of this parameter. The issue is in this line

.FirstOrDefault(_ => _.Parameters.All(arg => _container.CanResolve(arg.ParameterType)))

CanResolve should check if it contains DependencyAttribute and if it has then check if it's registered with this name. Something along these lines

  private bool CanResolve(IUnityContainer container, ParameterInfo arg)
                {
                    var dependencyAttributes = arg.GetCustomAttributes(false).OfType<DependencyAttribute>().ToList();
                    string name = dependencyAttributes.FirstOrDefault()?.Name;
                    
                    if (arg.ParameterType.IsGenericType)
                    {
                        var gerericType = arg.ParameterType.GetGenericTypeDefinition();
                        if ((gerericType == typeof(IEnumerable<>)) ||
                            gerericType.IsClass ||
                            IsRegistered(gerericType))
                        {
                            return true;
                        }
                    }

                    return IsRegistered(arg.ParameterType);

                   bool IsRegistered(Type t) => string.IsNullOrEmpty(name)
                        ? container.IsRegistered(t)
                        : container.IsRegistered(t, name);
                }

Hello @MistyKuu
Thank you, fixed here
I will update the package in 1 hr

What if you have named string or enum? Your solution just returns true but it should use named dependency

Fixed here > f1e2891