Asp.net-Mvc

使用 Autofac 將依賴項注入自定義 Web API 操作過濾器屬性

  • April 25, 2014

我正在嘗試解決AuthorizeAttribute我用來在 MVC4 應用程序中裝飾我的 API 控制器的自定義依賴項。問題是我不斷獲得NullReferenceException我在自定義過濾器中使用的服務依賴項。這是我的 Autofac 配置:

public static class WebApiConfig
{
   public static void Register(HttpConfiguration config)
   {
       var builder = new ContainerBuilder();
       builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
       builder.RegisterType<UnitOfWork>().As<IUnitOfWork>().InstancePerApiRequest();
       builder.RegisterType<DatabaseFactory>().As<IDatabaseFactory>().InstancePerApiRequest();
       builder.RegisterAssemblyTypes(typeof(UserProfileRepository).Assembly)
           .Where(t => t.Name.EndsWith("Repository"))
           .AsImplementedInterfaces().InstancePerApiRequest();

       builder.RegisterAssemblyTypes(typeof(IUserProfileMapper).Assembly)
           .Where(t => t.Name.EndsWith("Mapper"))
           .AsImplementedInterfaces().InstancePerApiRequest();

       builder.RegisterAssemblyTypes(typeof(UserProfileSvc).Assembly)
           .Where(t => t.Name.EndsWith("Svc"))
           .AsImplementedInterfaces().InstancePerApiRequest();

       builder.RegisterWebApiFilterProvider(config);
       var container = builder.Build();
       var resolver = new AutofacWebApiDependencyResolver(container);
       config.DependencyResolver = resolver;
   }
}

和我的自定義授權過濾器:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
   public IAuthenticationSvc _authenticationSvc;
   protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext)
   {
       if (!base.IsAuthorized(actionContext))
       {
           return false;
       }
       var trueUserId = WebSecurity.CurrentUserId;

       if (_authenticationSvc.GetUsersRoles(trueUserId).Any(x => x == "Admin")) return true;
       // NullReferenceException on _authenticationSvc
    }
}

根據官方文件,所有需要的是:

var builder = new ContainerBuilder();
builder.RegisterWebApiFilterProvider(GlobalConfiguration.Configuration);

但這似乎也不起作用。感謝任何幫助。

您應該為您的屬性配置屬性注入

public class MyAuthorizeAttribute : AuthorizeAttribute
{
   public IAuthenticationSvc AuthenticationSvc { get; set; }
}

和建設者

builder.RegisterType<MyAuthorizeAttribute>().PropertiesAutowired();

我認為 Autofac 的文件為 WebApi 操作過濾器提供了更簡單的解決方案。

public interface ServiceCallActionFilterAttribute : ActionFilterAttribute
{
 public override void OnActionExecuting(HttpActionContext actionContext)
 {
   // Get the request lifetime scope so you can resolve services.
   var requestScope = actionContext.Request.GetDependencyScope();

   // Resolve the service you want to use.
   var service = requestScope.GetService(typeof(IMyService)) as IMyService;

   // Do the rest of the work in the filter.
   service.DoWork();
 }
}

它不是“純 DI”,因為它使用服務定位器,但它很簡單並且適用於請求範圍。您無需擔心為每個 WebApi 控制器註冊特定的操作過濾器。

來源: http ://autofac.readthedocs.io/en/latest/integration/webapi.html#provide-filters-via-dependency-injection

引用自:https://stackoverflow.com/questions/23301227