One of the new features of the Dependency Inject (DI) components from MVC3 is something called a IFilterProvider. The purpose of this component is to provide a simpler way for MVC applications to interact with filters (action, exception, result, etc.). In the previous versions, trying to achieve something like providing DI support to filters was doable, it just required deeper integration into the MVC runtime. The IFilterProvider interface is defined as: public interface IFilterProvider {
IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor);
}As you can see, it’s a pretty simple interface that can enable lots of opportunities if used in the right context. The MVC bits ship with an implementation named FilterAttributeFilterProvider that parses the attributes defined on actions and controllers and returns an aggregated list for the runtime to process. So, how can we leverage this class to provide DI to these attributes? Let’s take a look :) Injecting Dependencies into Attributes
For this sample, I will use Ninject as the DI container to inject, via properties, dependencies into the attributes. The dependency is a simple IMessageService:public interface IMessageService {
string GetMessage(string action);
}public class MessageService : IMessageService {
public string GetMessage(string action) {
return string.Format("I'm in action '{0}'!", action);
}
}Read more: Javier G. Lozano
IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor);
}As you can see, it’s a pretty simple interface that can enable lots of opportunities if used in the right context. The MVC bits ship with an implementation named FilterAttributeFilterProvider that parses the attributes defined on actions and controllers and returns an aggregated list for the runtime to process. So, how can we leverage this class to provide DI to these attributes? Let’s take a look :) Injecting Dependencies into Attributes
For this sample, I will use Ninject as the DI container to inject, via properties, dependencies into the attributes. The dependency is a simple IMessageService:public interface IMessageService {
string GetMessage(string action);
}public class MessageService : IMessageService {
public string GetMessage(string action) {
return string.Format("I'm in action '{0}'!", action);
}
}Read more: Javier G. Lozano
0 comments:
Post a Comment