I am trying to keep this method as generic as possible. I am passing in a dynamic class. I want to create an instance of that class so that I can return it back to my controller. I am stuck on creating the instance. Here is what I have so far
This is how I call it from my controller
public async Task<IActionResult> GetClassById(Guid id)
{
return Ok(await _contribRepo.Get<MyModelClass>(id));
}
Here are the methods that take in a class type of T and send back the type T back to my controller
public async Task<T> Get<T>(Guid id) where T : class
{
var component = CommonHelper.GetAssemblyNameContainingType(default(T));
using (var connection = new SqlConnection(_connectionString))
{
await connection.OpenAsync();
component = await connection.GetAsync<T>(id);
}
return component;
}
public static object GetAssemblyNameContainingType<T>(T? typeName) where T : class
{
var type = Assembly.GetExecutingAssembly()
.GetTypes()
.FirstOrDefault(x => x.Name == typeName.ToString()); <----typeName is null
var obj = Activator.CreateInstance(type);
return obj;
}
Aucun commentaire:
Enregistrer un commentaire