Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC - adding action filters programmatically

I've been doing a bit of research regarding action filters and wondered if there was a way to add them programmatically to controllers??

To give some context, I'd like to add a logging filter if logging is configured in the web.config, otherwise I don't want the filter to exist in the execution chain of each action method.

I appreciate I can put a check in the actual filter code itself to see if logging is enabled but don't want to have to do this is possible.

Many thanks!

like image 468
Tim Peel Avatar asked Nov 06 '22 22:11

Tim Peel


1 Answers

A better solution would be to use the null object pattern.

Your filter would log normally (its job is to log, not to decide how to log or what to log to, necessarily), but by default the actual logger would be an implementation that does nothing. If it's configured, the logger instance will be an implementation that logs as configured.

A simple factory could make the decision of which logger implementation to deliver to the filter or any IOC container could be configured to handle it.

like image 51
Matt Hinze Avatar answered Nov 14 '22 23:11

Matt Hinze