z4kn4fein / stashbox

A lightweight, fast, and portable dependency injection framework for .NET-based solutions.
https://z4kn4fein.github.io/stashbox
MIT License
141 stars 10 forks source link

Base class InjectionMethod not populated #103

Closed mgth closed 3 years ago

mgth commented 3 years ago

Dependency properties in base class are OK, but method is not injected. by the way, I did not find a way to inject methods without using attributs (or declaring my own attribut). Is there one?

   public class A
    { }
    public class B
    { }

    public class BaseClass
    {
        [Dependency]
        public A A { get; set; }
        public bool DoneA { get; set; }

        [InjectionMethod]
        public void InjectA()
        {
            DoneA = true;
        }
    }

    public class MainClass : BaseClass
    {
        [Dependency]
        public B B { get; set; }
        public bool DoneB { get; set; }

        [InjectionMethod]
        public void InjectB()
        {
            DoneB = true;
        }
    }

    public class BaseClassMethod
    {
        [Fact]
        public void Test()
        {
            var container = new StashboxContainer();
            container.Register<A>().Register<B>().Register<MainClass>();

            var main = container.Resolve<MainClass>();

            Assert.IsType<B>(main.B);
            Assert.IsType<A>(main.A);

            Assert.True(main.DoneA);
            Assert.True(main.DoneB);
        }
    }   
z4kn4fein commented 3 years ago

Thanks for reporting, and for the PR! Yes, there is an additional method to achieve something similar, you can configure an initializer delegate on registration: .Register<MainClass>(c => c.WithInitializer(mainClass => mainClass.InjectB()));

To resolve dependencies, you can use a delegate with an extra IDependencyResolver parameter like: .Register<MainClass>(c => c.WithInitializer((mainClass, resolver) => mainClass.InjectB(resolver.Resolve<B>())));

z4kn4fein commented 3 years ago

Released in v3.6.3