samedi 19 janvier 2019

how to create by reflection constructor for access to repository

My goal is to call the method from class that is the repository. I have poor knowledge of reflection and I don't even know if it is possible.

Type model = AssemblyHelper.GetTypeByClassName(Assembly.GetExecutingAssembly(), modelName + MappingColums.Tokens.Validation);

here I'm getting assembly and then info aboute class ProductValidation, modelName = Product, MappingColums.Tokens.Validation = Validation

MethodInfo method = model.GetMethods().FirstOrDefault(x => x.Name == MappingColums.Tokens.Get + modelName && x.GetParameters().Count() == 0);

lookup for metod call GetProduct, MappingColums.Tokens.Get = Get + modelName = Product

and then for testing purpose I'm creating instance of ProductValidation for invoke method

ProductValidation test = new ProductValidation(repositoryProduct);
object result = method.Invoke(test, null);

In the class that I want to use above code for testing I had to add:

private IProductRepository repositoryProduct;
public ImportValidation(IProductRepository repoProduct)
{
    repositoryProduct = repoProduct;
}

I would like to use var instance = Activator.CreateInstance(); for creating ProductValidation but I don't know how to re-write the above test to reflection style. In other words, I do not know how to create by reflection repositoryProduct attribute for ProductValidation constractor.

public class ProductValidation
{
    private IProductRepository repositoryProduct;

    public ProductValidation(IProductRepository repoProduct)
    {
        repositoryProduct = repoProduct;
    }

    public ICollection<Product> GetProduct()
    {
        return repositoryProduct.Products.ToList();
    }

}

Thanks!





Aucun commentaire:

Enregistrer un commentaire