I’m not sure if/how I can check that the constructor actually exists before calling activator in this code (untested so might have bugs but hopefully the intention is clear).
Its as if I wanted a template constraint that says “where T has a constructor with signature S”.
public class EntityContainerFactory
{
public EntityContainerFactory(string sqlServerName, string databaseName, string metaData)
: this(sqlServerName, databaseName, metaData, "System.Data.EntityClient")
{
}
public EntityContainerFactory(string sqlServerName, string databaseName, string metaData, string dataProviderName)
{
SqlServerName = sqlServerName;
DatabaseName = databaseName;
Metadata = metaData;
DataProviderName = dataProviderName;
}
// --> IS THERE ANY WAY TO CHECK THAT T HAS
// A CONSTRUCTOR THAT TAKES AN ENTITY CONNECTION?
public T Create<T>()
{
return (T)Activator.CreateInstance(typeof(T), CreateEntityConnection());
}
EntityConnection CreateEntityConnection()
{
SqlConnectionStringBuilder sqlBuilder = new SqlConnectionStringBuilder();
sqlBuilder.DataSource = SqlServerName;
sqlBuilder.InitialCatalog = DatabaseName;
sqlBuilder.IntegratedSecurity = true;
EntityConnectionStringBuilder entityBuilder = new EntityConnectionStringBuilder();
entityBuilder.Provider = DataProviderName;
entityBuilder.ProviderConnectionString = sqlBuilder.ToString();
entityBuilder.Metadata = Metadata;
return new EntityConnection(entityBuilder.ConnectionString);
}
public string DatabaseName { get; set; }
public string SqlServerName { get; set; }
public string DataProviderName { get; set; }
private string metaData;
public string Metadata
{
get
{
string result;
if (!this.metaData.StartsWith("res://"))
{
result = string.Format(@"res://*/{0}.csdl|res://*/{0}.ssdl|res://*/{0}.msl", this.metaData);
}
else
{
result = this.metaData;
}
return result;
}
set
{
this.metaData = value;
}
}
}
Have you considered using interfaces instead of factories? You can get much better results, and you don’t run into problems like this.
Anyway:
Only works for parameterless constructors. When you have that constraint, you can do the following, without reflection:
You’re going to have to check manually.