When you build a service based on ADO.NET Data Services
platform you should specify a data model that will be used as a parent for a
creating web service. For REST-service a data model is an essential component
because a web service gives access to these data.
A data model is defined in a generic-parameter of
DataService<> base class. In this case when you access to a service
infrastructure, ADO.NET Data Services instances a data model automatically and
works with it. As a result, a default constructor is used without any
parameters.
Listing 1 - Simple web service
public class WebDataService1 : DataService<NorthwindEntities>
{
}
If a data model doesn't have a constructor without
parameters, infrastructure of ADO.NET Data Services can't create any instance
of this type. It is the reason you'll get an error message when try to access
to such service. This situation is well-spread. That's why many developers
prefer to avoid default constructors.
To resolve this problem you should override a way to
instantiate a data model and use a necessary constructor of a data model. You
should override CreateDataSource method to get own algorithm of instantiate of
a data model. As result, this method returns a type that is specified in a
generic-parameter of a base class at a web service definition. By default this
method accesses to CreateDataSource method of a base class which tries to find
a default constructor and create an object.
Listing 2 - The definition of instance mode of data
model
protected override NorthwindEntities CreateDataSource()
{
return base.CreateDataSource();
}
If a correct work of a web service demands of redefine logic
of a data model creation then you need to build a model manually and use a
suitable constructor. Also in this method it is possible to use a reference to IoC-container
or implement based on Dependency Injection principle. In the simplest case an
instance of a data model can be created and get a string of a connection with a
server of databases.
Listing 3 - The definition of instance mode of data
model
protected override NorthwindEntities CreateDataSource()
{
return new NorthwindEntities(@"some connection string");
}
Thus, CreateDataSource method will be called every time when
hosting-environment needs to instantiate a data model.