asp.net-mvc - 使用 Autofac 将依赖项注入(inject)自定义 Web API 操作过滤器属性

标签 asp.net-mvc asp.net-web-api dependency-injection autofac action-filter

我正在尝试解决我的自定义 AuthorizeAttribute 的依赖关系,我用它来装饰 MVC4 应用程序中的 API Controller 。问题是我在自定义过滤器中使用的服务依赖项上不断收到 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
     }
}

根据official docs所需要的只是:

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

但这似乎也不起作用。感谢任何帮助。

最佳答案

我认为 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 Controller 注册特定的操作过滤器。

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

关于asp.net-mvc - 使用 Autofac 将依赖项注入(inject)自定义 Web API 操作过滤器属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23301227/

相关文章:

c# - Web Api - 同时执行几个请求时响应真的很慢

java - 如何使用带参数的自定义注释查找 CDI bean?

javascript - 局部 View 渲染不正确(ASP.NET MVC)

c# - 如何实现类似SO的url重写

asp.net-mvc - 您想要完全用代码创建 View 的 ASP.NET MVC View 引擎吗?

c# - 为非常简单的类调整和简化 DataContract 序列化?

c# - MVC 5 - 尝试通过编辑操作修改图像失败

c# - 带有包含字典的参数的 Api Controller 中的 JSON.Net 始终为空

c# - 使用简单的注入(inject)器基于调用链动态注入(inject)依赖

c# - 构造函数注入(inject)和被注入(inject)依赖项的初始化