AutoFac: Inject NULL values

江枫思渺然 提交于 2019-11-30 19:15:47

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);

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.

To solve this problem, I have created the IPrincipalFactory interface that can obtain the current principal without going through AutoFac:

public AuthorizationValidator : IAuthorizationValidator
{
  public AuthorizationValidator(IDataAccess dataAccess, IPrincipalFactory principalFactory)
  {
     // Save injected objects
     _dataAccess = dataAccess;
     _principal = principalFactory.GetCurrentPrincipal();
  }

  public bool CheckPermission(Guid objectId, Action action)
  {
     // Same as previous example
     ...
  }
}

public interface IPrincipalFactory
{
  IPrincipal GetCurrentPrincipal();
}

For the ASP.NET application I would register the following object as IPrincipalFactory:

public class IAspNetPrincipalFactory : IPrincipalFactory
{
  public IPrincipal GetCurrentPrincipal() => HttpContext.Current?.User;
}

Although this works, I am not completely happy with this solution.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!