Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Third party dll's static private object causing error in my .NET code

Tags:

c#

.net

I use one third party dll and make some function call. Sometimes this function call fails. So I reinitialize the object and again make the function call. However, it still fails. If I stop my code execution and restart it, my function call again works fine.

I used a decompiler over this third party dll and realized that internally in the dll's class, there is a static object which is responsible for this exception. When I restart my program, the static object has to reinitialize and then my code works. Is it possible that I can force this using code? Basically, I want to ensure that even the static objects inside the class inside the dll get reinitialize when I make my object. I cannot restart my .NET program in production.

like image 352
Avdhut Vaidya Avatar asked Oct 30 '25 22:10

Avdhut Vaidya


1 Answers

You can use Reflection library to do it:

    var prop = s.GetType().GetField("ThePrivateStaticObjectName",
          System.Reflection.BindingFlags.NonPublic
        | System.Reflection.BindingFlags.Instance);
    prop.SetValue(s, "new value");

and a generic method to do it for any objects:

public static void SetPrivatePropertyValue<T>(T obj, string propertyName, object newValue)
{
    // add a check here that the object obj and propertyName string are not null
    foreach (FieldInfo fi in obj.GetType().GetFields(BindingFlags.Instance | BindingFlags.NonPublic))
    {
        if (fi.Name.ToLower().Contains(propertyName.ToLower()))
        {
            fi.SetValue(obj, newValue);
            break;
        }
    }
}
like image 57
Ali Adlavaran Avatar answered Nov 02 '25 12:11

Ali Adlavaran