解决未注册的服务时,防止Simple Injector引发异常 [英] Prevent Simple Injector to throw an exception when resolving an unregistered service

查看:53
本文介绍了解决未注册的服务时,防止Simple Injector引发异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道Simple Injector是否可以选择在 GetInstance(Of TService)返回 Nothing 时停止引发异常?现在似乎正在抛出它们,因为我有两个请求来获取实例,它不存在,并且抛出异常。



有没有办法防止默认值行为,某处的设置还是其他?

解决方案

绝对有一种简单的方法。 SimpleInjector.Container 实现 System.IServiceProvider ,它定义了对象GetService(类型)方法。未注册类型时,此方法返回 null IServiceProvider 是显式实现的,这意味着它在正常使用下不会显示,因此您必须转换 Container IServiceProvider ,如下所示:

  IServiceProvider provider =容器; 
对象实例= provider.GetService(typeof(MyClass));

或者您可以在此之上定义扩展方法:

  public static bool TryGetInstance< TService>(
此Container容器,出自TService实例)
其中TService:类
{
IServiceProvider提供程序=容器;
instance =(TService)provider.GetService(typeof(TService));
返回实例!= null;
}

我必须承认此功能有点隐藏。在参考库中目前唯一说明此方法。 p>

请注意,通常最好注册空对象模式实现(没有任何行为的空实现),而不是调用 TryGetInstance 方法。注入空对象使应用程序不必担心空引用,这使您的应用程序代码更易于理解和测试。


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 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.

这篇关于解决未注册的服务时,防止Simple Injector引发异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆