简体   繁体   中英

Interface and wrapper, custom model binder, or ActionFilter for providing common class to Controllers?

I need to provide my controller action methods access to a common class instance (lets call it UserSessionInfo) containing custom application user information.

At the moment its pulled directly from the http session by a base controller but Im trying to remove all dependencies on HTTPContext dependent objects to make the controllers cleaner and more testable.

My understanding is that there are three possible solutions,

  1. Inject it into the controller constructor
  2. ActionFilter to provide the UserSessionInfo to each action method.
  3. IModelBinder implementation to provide the UserSessionInfo to each action method.

I have a decent understanding of 1. Struggling to grok the differences between 2 and 3.

Any help appreciated.

Thanks,

Matt

The biggest difference between ActionFilters and ModelBinders is what they cant do, their coupling and developer expectation.

A modelBinder is executed before the actionfilter its specifically to bind request data to a model. it does not know what action its executing on. It is coupled to the binding process

An action filter knows about the action and its parameters the actionfilter exeutes after modelbinder and can change the data returned by the modelbinder. It is coupled to the executing action

Developer expectation is probably the biggest difference. ModelBinders are expected to be relatively light-weight parsing, extracting and populating objects only.

Actionfilters are expected to 'do stuff', make decisions, affect the processing pipeline under certain conditions.

Hope these loose guidelines are useful!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM