Wednesday, August 29, 2007

ObjectDataSource with objects having parameterized constructor

The ObjectDataSource control will create an instance of the source object, call the specified method, and dispose of the object instance all within the scope of a single request, if your object has instance methods instead of static methods (Shared in Visual Basic). Therefore, your object must be stateless. That is, your object should acquire and release all required resources within the span of a single request.

You can control how the source object is created by handling the ObjectCreating event of the ObjectDataSource control. You can create an instance of the source object, and then set the ObjectInstance property of the ObjectDataSourceEventArgs class to that instance. The ObjectDataSource control will use the instance that is created in the ObjectCreating event instead of creating an instance on its own.

<asp:objectdatasource id="ObjectDataSource1" typename="Samples.AspNet.CS.EmployeeLogic" onobjectcreating="NorthwindLogicCreating" selectmethod="GetAllEmployees" runat="server">
</asp:objectdatasource>



and have a method defined as


 private void NorthwindLogicCreating(object sender, ObjectDataSourceEventArgs e)
{
// Create an instance of the business object using a non-default constructor.
EmployeeLogic eLogic = new EmployeeLogic("Not created by the default constructor!");

// Set the ObjectInstance property so that the ObjectDataSource uses the created instance.
e.ObjectInstance = eLogic;
}


No comments:

 
Dotster Domain Registration Special Offer