Today I got into some code reviewing of an Item Event Receiver using Enterprise Library for data access. The problem occurred when registering the Event Receiver for a SharePoint List using the object model (SPList.EventReceivers.Add)
Exception has been thrown by the target of an invocation.
Here's a simplified view into the code:
public class MyEventReceiver: SPItemEventReceiver
{
MyDataAccess da = new MyDataAccess();
public override void ItemAdded(SPItemEventProperties properties)
{
...
}
}
public class MyDataAccess
{
public MyDataAccess()
{
Microsoft.Practices.EnterpriseLibrary.Data.DatabaseFactory.CreateDatabase("MyDB");
}
...
}
Apparently when the Event Receiver is registered it instantiates the MyDataAccess class which in turn calls the EntLib method in its constructor. This is what causes the exception.
A solution is to instantiate the MyDataAccess class in the methods rather than on event receiver initialisation:
public class MyEventReceiver: SPItemEventReceiver
{
public override void ItemAdded(SPItemEventProperties properties)
{
MyDataAccess da = new MyDataAccess();
...
}
}