Thursday, September 9, 2010

Contraceptive Pill Microgynon 30 Diarrhea

filters and injecting dependencies ...

Hello today I would like a bit closer MvcExtensions global filters and one of the applications that will be with me in the system has by this mechanism.

simple problem: We easily be able to keep up information about the last time the user viewed the page or record made by his actions. When I first approached this problem came to me two solutions:
-First: Create BaseController from which all others inherit a method that will have to be carried out whenever execute a controller action.
-Second: Use filters to be imposed on the controller.

first solution seems quite fun but is at odds with the principle of the controller should not have in the logic. Moreover, it is difficult testable by such treatment. So I decided to take advantage of the second. As it turned out the problem associated with the attributes needed to inject dependencies is to perform a particular activity. Poszperałem a little bit and I found MvcExtension mechanism called global filters. By the way it is implemented in version 3 of the MVC framework.

UpdateUserLastActivityFilter
As I said before the first simple filter that I used is updating the last activity user. Same attribute is simple. If a user is logged on to the class calls the UserService that updates its activity. The attribute looks like this:
 [AttributeUsage (AttributeTargets.Method  
{get;
private set;}


public void OnResultExecuting (ResultExecutingContext filterContext)


{} public void

OnResultExecuted (ResultExecutedContext filterContext)
{
Check.Argument.IsNotNull (filterContext, "filterContext");

string username = filterContext.HttpContext.User.Identity.IsAuthenticated? filterContext.HttpContext.User.Identity.Name: null;

if (string.IsNullOrEmpty (username)) {

UserService.UpdateLastActivity (username);

}}}


We already have attribute now must find a way to inject UserService to this attribute. The library is defined MvcExtension special interface which helps us in this task. Called ConfigureFilterBase. We will implement it as Bootstrapper task. It looks like this: public class

RegisterGlobalFilters: ConfigureFiltersBase

{protected override void Configure (IFilterRegistry registry) {
registry.Register
\u0026lt;AccountController, UpdateUserLastActivityAttribute> ()
. \u0026lt;HomeController, UpdateUserLastActivityAttribute> Register ; ();}

}
As you can see records filters are similar to types in the IoC container. It looks like this that serve as the first type of the controller and another the following are the filters which attaches to it. Such a procedure enable injection of the necessary interfaces to the attributes. In addition, we no longer hand controller decorate this action.
 So much in terms of global filters. As you can see MvcExtension has many interesting solutions. Many of them will be available in future versions of Asp.net MVC. 


0 comments:

Post a Comment