I need to register an Event Handler for a class which is generated by a Template – the T4 Template within the EntityFramework.
Currently, we have edited the generated code to register the handler within the Constructor of the generated class (the Model Context).
Current code:
public MyAppContext(string connectionString)
: base(connectionString, ContainerName)
{
this.ContextOptions.LazyLoadingEnabled = true;
// Register the event handler
this.Connection.StateChange += Connection_StateChange;
}
The problem is, if the code is ever re-generated in the future, then the above code will be clobbered and the Event Handler will no longer get hooked up…
Code re-generation happens automatically from the smallest thing such as opening the EF Designer and moving a Table around on the canvas! So its imperative we DO NOT rely on leaving the custom code in the generated class.
Is there anyway we can put the registration in a partial class and leave the generated code untouched???
EG is there some sort of event that will always be fired once a constructor is called ?
The answer to this problem is to edit the T4 Template to put in a method call at the end of the Constructor.
This method, in the context of partial classes generated by a template, needs to be a partial method.
The template needs to contain a definition for the partial method.
Then your custom partial class can implement that method and it will be called by the Constructors defined in the generated partial class – now you can regenerate that partial class as many times as you like and be guranteed that the partial method will always be called – assuming no one edits the template.
If someone does edit the template and removes the definition of the partial method, then you will get a compiler error – easy to fix.
If someone edits the template and removes the call to the partial method from the Constructor, then unfortunately, the compiler can’t help you – something to be aware of!
Here is my solution in tid-bits:
A snippet of the constructor and partial method definition in the T4 Template code ‘MyApp.Context.tt’ (see here for a great explanation of T4 syntax and its use within the EntityFramework):
The custom partial class which implements the partial method and wires up the event handler: