dadhi / DryIoc

DryIoc is fast, small, full-featured IoC Container for .NET
MIT License
1.03k stars 122 forks source link

how to let it auto select made.Of #518

Closed sgf closed 2 years ago

sgf commented 2 years ago

what i want: 1.first use the empty public constructor

if not has then

  1. use constructor with Resolvable arguments
dadhi commented 2 years ago

Hi @sgf,

You can do it like this:

using NUnit.Framework;

namespace DryIoc.IssuesTests
{
    [TestFixture]
    public class GHIssue518_Select_default_then_resolvable_constructor : ITest
    {
        [Test]
        public void Example()
        {
            var c = new Container();

            c.Register<A1>(made: Made.Of(
                req => FactoryMethod.DefaultConstructor().Invoke(req) 
                    ?? FactoryMethod.ConstructorWithResolvableArguments(req)));

            c.Register<A2>(made: Made.Of(
                req => FactoryMethod.DefaultConstructor().Invoke(req) 
                    ?? FactoryMethod.ConstructorWithResolvableArguments(req)));

            c.Register<B>();

            var a1 = c.Resolve<A1>();
            Assert.IsNotNull(a1);

            var a2 = c.Resolve<A2>();
            Assert.IsNotNull(a2.B);
        }

        class A1 
        {
        }

        class A2
        {
            public readonly B B;
            public A2(B b) => B = b;
        }

        class B {}
    }
}
sgf commented 2 years ago

Hi @sgf,

You can do it like this:

using NUnit.Framework;

namespace DryIoc.IssuesTests
{
    [TestFixture]
    public class GHIssue518_Select_default_then_resolvable_constructor : ITest
    {
        [Test]
        public void Example()
        {
            var c = new Container();

            c.Register<A1>(made: Made.Of(
                req => FactoryMethod.DefaultConstructor().Invoke(req) 
                    ?? FactoryMethod.ConstructorWithResolvableArguments(req)));

            c.Register<A2>(made: Made.Of(
                req => FactoryMethod.DefaultConstructor().Invoke(req) 
                    ?? FactoryMethod.ConstructorWithResolvableArguments(req)));

            c.Register<B>();

            var a1 = c.Resolve<A1>();
            Assert.IsNotNull(a1);

            var a2 = c.Resolve<A2>();
            Assert.IsNotNull(a2.B);
        }

        class A1 
        {
        }

        class A2
        {
            public readonly B B;
            public A2(B b) => B = b;
        }

        class B {}
    }
}

many thanks