I was wondering if Simple Injector has an option to stop throwing exceptions whenever GetInstance(Of TService)
returns Nothing
? It appears to be throwing them now because I have two requests to get an instance, it's not there, and it throws the exception.
Is there a way to prevent the default behavior, a setting somewhere, or something else?
There absolutely is a simple way of doing this. The
SimpleInjector.Container
implements System.IServiceProvider, which defines an object GetService(Type) method. This method returnsnull
when a type is not registered. TheIServiceProvider
however, is implemented explicitly, which means it doesn't show up under normal use, so you have to cast theContainer
toIServiceProvider
, as shown below:Or you can define an extension method on top of this:
I must admit that this feature is a bit hidden. The only place this method is currently explained is in the reference library.
Do note that in general it is much better to register Null Object Pattern implementations (empty implementations without any behavior) instead of calling an
TryGetInstance
method. Injecting Null Objects prevents the application from having to worry about null references, which makes your application code easier to understand and easier to test.