You can use Linq Expressions as explained in this blog post. In your case, it would be
ConstructorInfo ctor = typeof(LoginView).GetConstructors().First();
ObjectActivator<LoginView> createdActivator = GetActivator<LoginView>(ctor);
LoginView instance = createdActivator();
In case the link goes down, this is ObjectActivator
delegate
delegate T ObjectActivator<T>(params object[] args);
and the GetActivator
method
public static ObjectActivator<T> GetActivator<T>
(ConstructorInfo ctor)
{
Type type = ctor.DeclaringType;
ParameterInfo[] paramsInfo = ctor.GetParameters();
//create a single param of type object[]
ParameterExpression param =
Expression.Parameter(typeof(object[]), "args");
Expression[] argsExp =
new Expression[paramsInfo.Length];
//pick each arg from the params array
//and create a typed expression of them
for (int i = 0; i < paramsInfo.Length; i++)
{
Expression index = Expression.Constant(i);
Type paramType = paramsInfo[i].ParameterType;
Expression paramAccessorExp =
Expression.ArrayIndex(param, index);
Expression paramCastExp =
Expression.Convert (paramAccessorExp, paramType);
argsExp[i] = paramCastExp;
}
//make a NewExpression that calls the
//ctor with the args we just created
NewExpression newExp = Expression.New(ctor,argsExp);
//create a lambda with the New
//Expression as body and our param object[] as arg
LambdaExpression lambda =
Expression.Lambda(typeof(ObjectActivator<T>), newExp, param);
//compile it
ObjectActivator<T> compiled = (ObjectActivator<T>)lambda.Compile();
return compiled;
}
One advantage to using this method over the generic method is that you can easily pass in parameters to your constructor but the disadvantage being more verbose code.