Prevent Simple Injector to throw an exception when

2019-03-30 17:42发布

问题:

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?

回答1:

There absolutely is a simple way of doing this. The SimpleInjector.Container implements System.IServiceProvider, which defines an object GetService(Type) method. This method returns null when a type is not registered. The IServiceProvider however, is implemented explicitly, which means it doesn't show up under normal use, so you have to cast the Container to IServiceProvider, as shown below:

IServiceProvider provider = container;
object instance = provider.GetService(typeof(MyClass));

Or you can define an extension method on top of this:

public static bool TryGetInstance<TService>(
    this Container container, out TService instance)
    where TService : class
{
    IServiceProvider provider = container;
    instance = (TService)provider.GetService(typeof(TService));
    return instance != null;
}

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.