Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass in the repository to an authorize attribute in ASP.NET MVC

I am castle Windsor and it works great for controller constructors in passing in the repository that is being used.

private IStoryRepository Repository;
public StoryController(IStoryRepository Repository)
{
    this.Repository = Repository;                   
}

Now I have an Action that is in the admin area to display the main admin menu. I have used a custom authorisation attribute which will just check that the logged in user is an admin (just an isAdmin flag in the users table)

 [AdminAuthorize]
 public ActionResult Menu()

 private IStoryRepository Repository;
 /// <summary>
 /// Initializes a new instance of the <see cref="AdminAuthorizeAttribute"/> class.
 /// </summary>
 public AdminAuthorizeAttribute(IStoryRepository Repository)
 {
     this.Repository = Repository;
 }

 /// <summary>
 /// Checks if the user is authorised
 /// </summary>
 /// <param name="httpContext">The HTTP context.</param>
 /// <returns>
 ///    <c>true</c> if authorized; otherwise, <c>false</c>.
 /// </returns>
 protected override bool AuthorizeCore(HttpContextBase httpContext)
 {
    return this.Repository.UserIsAdmin(httpContext.User.Identity.Name);
 }

How can I get Castle to pass the repository into attribute constructor like it does for a controller constructor?

like image 404
William Hurst Avatar asked Nov 15 '22 15:11

William Hurst


1 Answers

You basically have two options. Wrap the filter in a proxy, a good example of this can be found here.

Or, within your custom filter you can do an explicit container call. For example using StructureMap (I have no used castle extensively)

ObjectFactory.GetInstance(IStoryRepository)

There may be a third way which is to extend the ActionInvoker to do the injection but I am not sure how this would be done.

like image 114
madcapnmckay Avatar answered Dec 05 '22 01:12

madcapnmckay