AutoFac:注入NULL值 [英] AutoFac: Inject NULL values

查看:252
本文介绍了AutoFac:注入NULL值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用AutoFac在需要它的对象中注入当前主体.假设我有一个对象(AuthorizationValidator)正在执行安全检查.看起来像这样:

I want to use AutoFac to inject the current principal in the objects that need it. Suppose I have an object (AuthorizationValidator) that is performing security checks. It looks something like this:

public AuthorizationValidator : IAuthorizationValidator
{
  public AuthorizationValidator(IDataAccess dataAccess, IPrincipal principal)
  {
     // Save injected objects
     ...
  }

  public bool CheckPermission(Guid objectId, Action action)
  {
     // Check if we are authorized at all
     if (this.principal == null)
       return false;

     // Check the permission in the database
     ...
  }
}

对于我的Web应用程序,AuthorizationValidator已注册,我使用以下注册来注入主体:

For my web application the AuthorizationValidator is registered and I use the following registration to inject the principal:

builder.Register<IPrincipal>((c, p) => HttpContext.Current?.User);

其他类型的应用程序使用线程的主体或类似的东西.所有需要委托人的对象都会注入适当的委托人.

Other type of applications use the thread's principal or something similar. All object that require the principal get the proper principal injected.

如果未经授权进行呼叫,则AutoFac会引发异常,告诉我它无法提供IPrincipal对象,因为工厂返回了null.在这种情况下,可以使用空的主体,并且不应引发异常.

If a call is made without authorization, then AutoFac raises an exception telling me that it cannot provide the IPrincipal object, because the factory returned null. In this case, an empty principal is fine and shouldn't raise an exception.

推荐答案

在Autofac中文档,他们建议在这种情况下使用空对象模式 .您可以使用私有构造函数创建一个从IPrincipal接口继承的NullPrincipal类,该私有构造函数仅公开提供默认实例的readonly static字段.然后,您可以返回此实例,而不是返回null:

In the Autofac documentation they recommend to use the Null Object pattern for such scenarios. You could create a NullPrincipal class that inherits from the IPrincipal interface with a private constructor that only exposes a readonly static field which provides the default instance. Then you can return this instance instead of null:

builder.Register<IPrincipal>((c, p) => HttpContext.Current?.User ?? NullPrincipal.Default);

当然,您必须更新代码中检查主体是否为null的所有位置,并检查其是否等于NullPrincipal.Default.

Of course you would have to update all places in your code where you are checking if the principal is null and check if it is equal to the NullPrincipal.Default instead.

这篇关于AutoFac:注入NULL值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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