ipjohnson / Grace

Grace is a feature rich dependency injection container library
MIT License
336 stars 33 forks source link

Attribute [Import] is populated twice #277

Closed mgth closed 3 years ago

mgth commented 3 years ago

I could not tell until now, but I have a case where Injection has side effects and I noticed that injection within [Import] marked methods occurs twice

    public class Exported
    { }

    public interface ITest
    {
        int P { get; }
        int I { get; }
        int C { get; }
    }

    [Export(typeof(ITest))]
    public class Test : ITest
    {
        public int P { get; set; } = 0;
        private Exported _exported;

        [Import]
        public Exported InjectProperty
        {
            get => _exported;

            set
            {
                _exported = value;
                P++;
            }
        }

        public int I { get; set; } = 0;

        [Import]
        public void InjectMethod(Exported exported)
        {
            I++;
        }

        public int C { get; set; } = 0;
        public Test()
        {
            C++;
        }
    }

    public class GraceTest
    {
        [Fact]
        public void Test()
        {
            var container = new DependencyInjectionContainer();

            var assembly = Assembly.GetAssembly(typeof(Test));

            container.Configure(c => c
                .ExportAssembly(assembly).ExportAttributedTypes()
            );

            var test = container.Locate<ITest>();

            Assert.Equal(1,test.C);
            Assert.Equal(1,test.P);
            Assert.Equal(1,test.I);
        }
    }
ipjohnson commented 3 years ago

Ok I've pushed a fix for this to nuget as prerelease

mgth commented 3 years ago

Fine, works great, thanks a lot.

ipjohnson commented 3 years ago

cool, I'm going to close this out