lundi 5 décembre 2016

The calling of an instance method by using reflection throws TargetException.

I have MyServiceLibrary.dll which represents few classes such as UserStorageService, Storage, User. The service contains a storage and saves users into storage.

I created a new console application with new application domain inside it.

AppDomain masterDomain = AppDomain.CreateDomain("servicedomain");
string serviceLibraryPath = @"G:\Git\Service";
Assembly serviceAssembly = Assembly.LoadFrom(serviceLibraryPath);

Here I get all types which I use.

Type userType = serviceAssembly.GetType("MyServiceLibrary.User");
Type storageType = serviceAssembly.GetType("MyServiceLibrary.UserStorage");
Type userStorageServiceType = serviceAssembly.GetType("MyServiceLibrary.UserStorageService");

New instances of these types were creted into masterDomain.

var storage = masterDomain.CreateInstanceFromAndUnwrap(serviceLibraryPath, storageType.FullName);

var user = masterDomain.CreateInstanceFromAndUnwrap(serviceLibraryPath, userType.FullName);

var userStorageService = masterDomain.CreateInstanceFromAndUnwrap(
                    serviceLibraryPath, // assemblyFile 
                    userStorageServiceType.FullName, // typeName                                                           
                    false, // ignoreCase                                                        
                    BindingFlags.CreateInstance, // bindingAttr                                                                
                    default(Binder), // binder                                                            
                    new object[] {storage}, // args                                                                 
                    CultureInfo.CurrentCulture, // culture                                                                 
                    new object[] {} // activationAttributes
            );

All of my types which I used were inherited from MarshalByRefObject class. Now I want to add my new user.

MethodInfo addMethod = userStorageServiceType.GetMethod("Add");
addMethod.Invoke(userStorageService, new object[] { user });

I got an exception:

TargetException: The object does not match the target type.

In logfile I saw that the instance of UserStorageService was created. I can call a static method of this class, but instance methos don't work.





Aucun commentaire:

Enregistrer un commentaire