开发者

ASP.net MVC -How to use castle windsor's capability to resolve an object inside the view

I have the requirement where I need to make a call to my service from inside of my view. The service I need to call has dependencies to my repositories.

So instead of doing like - IUserService _userService = new UserService(new UserRepository() );

I would like to obtain the _userService object from Windsor, as it already has all the dependencies resolved.

How can I achieve this ?


The viewwhere I need to call the IUserService is _layout.cshtml inside the Shared Folder. Th开发者_如何学Pythonere is no controller specific to this. So where should I be injecting the dependency from?

The functionality I need inside the view is to check for Role based access which I have implemented via UserService. I have 2 choices - 1. Either to use COntext.User.IsInRole inside my view (which is not a testable piece of code) 2. Or call the my UserService from view (which is supported by tests). I had to choose lesser of two evils so I went with the 2nd choice.

Any inputs will be highly appreciated.


You asked for input. IMO you should not be making calls to a repository from within a view.

I can think of two better options.

Option 1

Put the users roles into a ViewModel which you then pass to the view. Then you query the ViewModel for the roles.

Option 2

Call a ChildAction on your AccountController and return a partial view. Something like this:

In your View:

Html.Action("GetUserRoles", "Account");

In your Controller:

[ChildActionOnly]
[Transaction]
public PartialViewResult GetUserRoles(string userId)
{
   var viewModel = userService.GetRolesForUser(userId);
   return PartialView(viewModel);
}

Now you can just inject IUserService via the Controller constructor. IMO Appart from simple iterations and similar stuff, Views should not contain any code, especially not data access code. That's the whole premise of the MVC pattern.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜