NReco + MVC Tutorial ASP.NET MVC integration with NReco infrastructure


Injecting Controller Dependencies

MvcControllerActivator (located in App_Start folder) supports controller definition in NReco IoC-container:
<component name="MyController" type="MyApp.Controllers.MyController" singleton="true" lazy-init="true">
	<property name="Dalc"><ref name="db"/></property>
</component>
Controller instance is requested by controller type (component name doesn't matter). If controller is not defined in IoC-container activator creates controller instance automatically (like default MVC controller activator).
Default IoC-config file location for controller definitions: config/web/controllers.xml.config

Controller Actions and Transactions

NReco MVC application has special MvcActionHandler that handles MvcActionEventArgs and invokes controller callback. This is recommended way for invoking controller code in transaction through NReco event broker:
AppContext.EventBroker.PublishInTransaction(this, new MvcActionEventArgs( () => {
	// inline controller action in transaction scope
}));
It is recommended to extract all significant controller-level actions into separate handler classes. The following example illustrates how to do that in common case:
  1. Define event arguments class that represents UI action context:
    public class MyActionEventArgs : EventArgs {
    	public MyActionEventArgs( /* action parameters: context, MVC models */ ) { }
    }
  2. Define action handler class:
    public class MyActionHandler {
    	public MyActionHandler(NReco.Application.EventBroker eventBroker) {
    		eventBroker.Subscribe<MyActionEventArgs>(RunAction);
    	}
    	public void RunAction(object sender, MyActionEventArgs args) {
    		/* action code */
    	}
    }
    Any dependencies could be declared either as constructor arguments or public properties.
    Note that you can avoid dependency from EventBroker class (and NReco.Application assembly); in this case you can bind handler with IoC-container EventBinder component.
  3. Configure handler component in IoC-container:
    <component name="mvcActionHandler" type="HandlerNamespace.MyActionHandler" singleton="true" lazy-init="false">
    	<constructor-arg index="0"><ref name="eventBroker"/></constructor-arg>
    	<!-- inject additional handler dependencies -->
    </component>
  4. Publish action event in controller method:
    AppContext.EventBroker.PublishInTransaction(this, new MyActionEventArgs( /* */ ));
    (Publish method can be used to avoid creation of transaction scope)