Подтвердить что ты не робот

Включение зависимостей в пользовательский атрибут фильтра действия веб-API с помощью Autofac

Я пытаюсь разрешить зависимости моего пользовательского AuthorizeAttribute, который я использую, чтобы украсить мои контроллеры API в приложении MVC4. Проблема в том, что я продолжаю получать 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);

Но это тоже не похоже на трюк. Цените любую помощь.

4b9b3361

Ответ 1

Вы должны настроить вложение свойств для вашего атрибута

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

и построитель

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

Ответ 2

В дополнение к @Toan Nguyen ответ, если у вас есть это...

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

... кажется, вам также нужна (или может понадобиться) первая строка ниже:

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

Ссылка: http://itprojectpool.blogspot.com.au/2014/03/autofac-di-on-action-filters.html

Ответ 3

Я думаю, что документация по 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