How to return NULL in an Autofac registration?
autofac, c#, exception
Solution
AFAIK, returning NULL in a registration will always throw an exception. For some ideas on how to handle that, check out this answer.
Problem
Is there a way to return null with autofac? I get a exception if I do this. In some cases I cant resolve a object and should return null. ``` m_builder.Register < IMyObject > ((c, p) => { //do something if (...) { //cant create/resolve object (error case) return null; } else { return new IMyObject(); } }).InstancePerHttpRequest(); ``` Is there a build-in way to do this with autofac? Edit: I want to return null. Or do something else to inform the user that the creation was not successful. If I return null this exception will be thrown: DependencyResolutionException: A delegate registered to create instances of 'IMyObject' returned null. Stacktrace: at Autofac.Core.Activators.Delegate.DelegateActivator.ActivateInstance(IComponentContext context, IEnumerable`1 parameters) at Autofac.Core.Resolving.InstanceLookup.Activate(IEnumerable`1 parameters) at Autofac.Core.Resolving.InstanceLookup.b__0() at Autofac.Core.Lifetime.LifetimeScope.GetOrCreateAndShare(Guid id, Func`1 creator) at Autofac.Core.Resolving.InstanceLookup.Execute() at Autofac.Core.Resolving.ResolveOperation.GetOrCreateInstance(ISharingLifetimeScope currentOperationScope, IComponentRegistration registration, IEnumerable`1 parameters) at Autofac.Core.Resolving.ResolveOperation.Execute(IComponentRegistration registration, IEnumerable`1 parameters) at Autofac.Core.Lifetime.LifetimeScope.ResolveComponent(IComponentRegistration registration, IEnumerable`1 parameters) at Autofac.ResolutionExtensions.TryResolveService(IComponentContext context, Service service, IEnumerable`1 parameters, Object& instance) at Autofac.ResolutionExtensions.ResolveService(IComponentContext context, Service service, IEnumerable`1 parameters) at Autofac.ResolutionExtensions.Resolve[TService](IComponentContext context, IEnumerable`1 parameters) at Autofac.ResolutionExtensions.Resolve[TService](IComponentContext context, Parameter[] parameters) at RestApi.Controllers.MyApiController.CreateEntityContext() in C:...