autofac / Autofac

An addictive .NET IoC container
https://autofac.org
MIT License
4.44k stars 836 forks source link

```Scope.TryResolve(FactoryTypes, out var Instance)``` throws #1396

Closed TonyValenti closed 9 months ago

TonyValenti commented 9 months ago

Describe the Bug

Maybe my expectaions are wrong, but I expect TryResolve to return false and never throw. Scope.TryResolve(Type, out var Instance) will throw an exception if the type has a required property that is not fulfilled.

using Autofac;
using Autofac.Features.ResolveAnything;

namespace ConsoleApp30 {
    internal class Program {
        static void Main(string[] args) {
            var Builder = new ContainerBuilder();

            var UnregisteredTypes = new AnyConcreteTypeNotAlreadyRegisteredSource()
                .WithRegistrationsAs(x => x.InstancePerLifetimeScope())
                ;

            Builder.RegisterSource(UnregisteredTypes);

            var Container = Builder.Build();
           //THIS SHOULD NOT THROW
            var I2 = Container.TryResolve(typeof(Bad), out _);
        }
    }

    public class Bad {
        private Bad() { }
    }

}

Expected Behavior

It should not throw.

Dependency Versions

I'm using the latest version of AutoFac.

tillig commented 9 months ago

From the docs

Both ResolveOptional() and TryResolve() revolve around the conditional nature of a specific service being registered. If the service is registered, resolution will be attempted. If resolution fails (e.g., due to lack of a dependency being registered), you will still get a DependencyResolutionException. If you need conditional resolution around a service where the condition is based on whether or not the service can successfully resolve, wrap the Resolve() call with a try/catch block.