views:

526

answers:

1

I've got a data provider that contains a collection of entities. I only want to be able to create a new entity through the data provider.

I.e, to create a new record I need to use:

Entity entity = Provider.AddNew();
enity.set_Properties... etc

My issue is that if I set my entities to Internal, System.Activator cannot create an Instance of them. Each of my Data Providers uses a Base class with the generic type of the entity passed through.

So at the moment my AddNew() method contains the following:

public T AddNew()
{
  T added = Activator.CreateInstance<T>();
  this.Collection.Add(added);
  return added;
}

It's obviously not the end of the world if I can instantiate a new entity manually outside of the Data Provider namespaces, but it seems pointless considering there's no way to ever save them, so why give the option to do so?

EDIT: Forgot to mention that all my providers, entities, etc are in the same namespace.

A: 

Don't use the Activator, which relies on a public constructor. Instead use reflection to find the parameterless constructor and then call it. Something along these lines:

Type t = typeof(MyType);
var parameterlessCtor = (from c in t.GetConstructors(
  BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance)
    where c.GetParameters().Length == 0
    select c).FirstOrDefault;
if(parameterlessCtor != null) instance = parameterlessCtor.Invoke(null);
ctacke