TryResolve Throws Exception

In our test suite, in many places, we use a concrete object. In other places, we put a mock object.

Problem is once we register the Mock object we cant remove it.

There is NO call for

IOC.Dispose<>()

There is a call for

IOC.Dispose()

which we dont want to do.

So what we did was to register a null

IOC.Register((ITheObject>null);

When we do this, the next time we come around to

if(IOC.TryResolve<ITheObjectl>() == null)
{
     IOC.Register<ITheObject>(new TheObject())
}

It throws an exception.

at System.RuntimeMethodHandle.InvokeMethod(Object target, Object arguments, Signature sig, Boolean constructor, Boolean wrapExceptions)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object parameters, CultureInfo culture)
at System.Reflection.ConstructorInfo.Invoke(Object parameters)
at NUnit.Framework.Internal.Reflect.Construct(Type type, Object arguments)
at NUnit.Framework.Internal.TypeWrapper.Construct(Object args)
at NUnit.Framework.Internal.Commands.ConstructFixtureCommand.<.ctor>b__0_0(TestExecutionContext context)
at NUnit.Framework.Internal.Commands.BeforeTestCommand.Execute(TestExecutionContext context)
at NUnit.Framework.Internal.Execution.CompositeWorkItem.PerformOneTimeSetUp()

So now we are putting a try catch around the TryReslove, which works but is not optimal.

Is this the best way to do this. Is there a bug.

The IOC Container should be immutable after AppHost is started, if you need a new container create a new AppHost instance.

ServiceStack’s IOC does support dispose:

Which is called when the AppHost is disposed.

Understood you support Dispose(); We wanted to Dispose<>().

What is confusing is, you dont expect TryReslove to throw an exception if whats being referenced contains a null.

Thanks

This uses the same code as the original Funq code which has been untouched for >10 years. Ideally it would’ve thrown an ANE if trying to register a null dependency, but I’ve updated to guard against NRE’s when resolving null deps in this commit.

FYI, I figured out why this crashed.

We were asking TryResolve to return our ILogger object, and there are multiple ILogger’s defined by our tools and other packages. In this case, a different packages ILogger was being registered, and we asked it to resolve it to our ILogger. Hence the exception.

Sorry about the confusion.

1 Like