Question

I am currently trying to set a field which I need in business logic which in this case is Lazy. (yes not the property, it is necessary to set the field) I get the error that Lazy can not be converted to Lazy as you can see:

Object of type 'BusinessLogic.Lazy1[System.Object]' cannot be converted to type 'BusinessLogic.Lazy1[BusinessLogic.ArtikelBLL]

I use this line to get a dynamic repository.

dynamic repository = Activator.CreateInstance(typeof(GenericRepository<>).MakeGenericType(typeArgs));

Then I try to set the value of the field but it fails:

fInfo.SetValue(obj, Lazy.From(() => repository.GetDataById(id)));

I have tried to solve it many different ways. Somehow I have to cast repository.GetDataById(id) to the Entity it is looking for, which in this case is ArtikelBLL (which i can get through pInfo.PropertyType). But by doing (ArtikelBLL)repository.GetDataById(id) it will not remain object orientated. Can anybody please help me with this?

Was it helpful?

Solution

The simplest way would be to just use a cast inside the lambda:

fInfo.SetValue(obj, new Lazy<GenericBLL>(
    () => (ArtikelBLL) repository.GetDataById(id)));

After all, that's the type the Lazy<T> wants.

EDIT: If you're trying to do this dynamically, I suggest you write a generic method like this:

public Lazy<T> CreateLazyDataFetcher<T>(dynamic repository)
{
    return new Lazy<T>(() => (T) repository.GetDataById(id));
}

Then call that method with reflection. (Using MethodInfo.MakeGenericMethod(...).Invoke(...))

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top