使用Unity 2和MVC 3将类注入Authentication属性

时间:2012-03-13 01:09:18

标签: c# asp.net-mvc-3 unity-container

我读了很多文章,指出如何做到这一点,即:

Stack overflow solution

Brad Wilsons excellent tutorial

这些似乎效果很好,但是当我遵循这里的一些指导原则时

Securing your ASP.NET MVC 3 Application

我好像来了一个收割机。我的问题是当我将AuthorizationAttribute添加为GlobalFilter而不是仅仅装饰控制器/操作时。虽然依赖解析器似乎被调用并设置我公开的[Dependancy]属性,当它实际到达我覆盖AuthorizeAttribute的OnAuthorization()方法的代码部分时,我的public [Dependency]属性为null。

当我从全局过滤器中删除它并装饰一个控制器时,它似乎有效。

如果需要更多信息,我可以发布代码。

编辑: 为了进一步扩展这里,我的一些代码是:

的global.asax.cs

 public static void RegisterGlobalFilters(GlobalFilterCollection filters)
    {                        
        // If I have this here the my [Dependency] attribute does not keep it's value
        // If I remove it and decorate the controller the [Dependency] attribute keeps it value
        filters.Add(new BasicAuthenticationAttribute());
        filters.Add(new HandleErrorAttribute());
    }

protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);

        // injection of services and data contexts
        var container = new UnityContainer();

        // injections for services
        RegisterUnityServices(container);

        // Filter provides to allow injection into attribute filters
        RegisterUnityFilters(container);

    }

    private void RegisterUnityServices(UnityContainer container)
    {
        container.RegisterType<IDataContext, CDAXDataContext>();

        container.RegisterType<IUploadService, UploadService>();
        container.RegisterType<IAuthenticationService, AuthenticationService>();

        // add more services here ...            
        DependencyResolver.SetResolver(new Models.UnityDependencyResolver(container));            
    }

    private void RegisterUnityFilters(UnityContainer container)
    {
        var oldProvider = FilterProviders.Providers.Single(f => f is FilterAttributeFilterProvider);
        FilterProviders.Providers.Remove(oldProvider);

        var provider = new UnityFilterAttributeFilterProvider(container);
        FilterProviders.Providers.Add(provider);            
    }

我的Unity课程取自brad wilsons的例子:

    public class UnityDependencyResolver : IDependencyResolver
{
    readonly IUnityContainer _container;

    public UnityDependencyResolver(IUnityContainer container)
    {
        this._container = container;
    }

    public object GetService(Type serviceType)
    {
        try
        {
            return _container.Resolve(serviceType);
        }
        catch
        {
            return null;
        }
    }

    public IEnumerable<object> GetServices(Type serviceType)
    {
        try
        {
            return _container.ResolveAll(serviceType);
        }
        catch
        {
            return new List<object>();
        }
    }
}

    public class UnityFilterAttributeFilterProvider : FilterAttributeFilterProvider 
{
    private IUnityContainer _container;

    public UnityFilterAttributeFilterProvider(IUnityContainer container)
    {
        _container = container;
    }

    public override IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
    {
        var filters = base.GetFilters(controllerContext, actionDescriptor);

        foreach (var filter in filters)
        {
            _container.BuildUp(filter.Instance);
        }

        return filters;
    }

    protected override IEnumerable<FilterAttribute> GetControllerAttributes(
                ControllerContext controllerContext,
                ActionDescriptor actionDescriptor)
    {

        var attributes = base.GetControllerAttributes(controllerContext,
                                                      actionDescriptor);
        foreach (var attribute in attributes)
        {
            _container.BuildUp(attribute.GetType(), attribute);
        }

        return attributes;
    }

    protected override IEnumerable<FilterAttribute> GetActionAttributes(
                ControllerContext controllerContext,
                ActionDescriptor actionDescriptor)
    {

        var attributes = base.GetActionAttributes(controllerContext,
                                                  actionDescriptor);
        foreach (var attribute in attributes)
        {
            _container.BuildUp(attribute.GetType(), attribute);
        }

        return attributes;
    }
}

My BasicAuthenticationAttribute的基础,我在其中设置了[Dependency]属性,但在 OnAuthorization 方法被触发时没有保持该值。

    public class BasicAuthenticationAttribute : AuthorizeAttribute
{
    [Dependency]
    public IAuthenticationService Authentication { get; set; }

    private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus)
    {
        validationStatus = OnCacheAuthorization(new HttpContextWrapper(context));
    }

    public override void OnAuthorization(AuthorizationContext filterContext)
    {
       // code here that uses the Authentication attribute but it's null
    }

1 个答案:

答案 0 :(得分:3)

你有没有解决这个问题? 我认为您需要在属性类中调用DependencyResolver ...不确定[Dependency]属性是否适用于此...所以在OnAuthorization方法调用中IAuthenticationService authentication = DependencyResolver.Current.GetService<IAuthenticationService>();