How do I inject a Class into a c# dll

90 views Asked by At

I've a dll with a bunch of classes and methods, it's part of an executable.

The dll will include the following

public class MyDep: IMyDep 
{
  public void aMethod() {return;}
}
public class MyClass : IMyClass
{
  public IMyDep Dep = new MyDep();
}

Now from another solution I will run MyApp.exe which will load the dll as one of its dependencies.

Before I run it I would like to define a mock MyDep class and inject it into the original dll. Ideally I want to write this process entirely in c# and automate it.

What's the best way to achieve this?

1

There are 1 answers

0
Axeltherabbit On BEST ANSWER
UPDATE

Rather than creating a new solution I decided to use a compiler symbol at least I won't have too many solutions in the project.

I changed MyDep to

public class MyDep: IMyDep 
{
#if APPIUM
  public void aMethod() {
   runMockCode();
   return;
  }

#else
  public void aMethod() {
   runProductionCode();
   return;
  }

#endif
}

And I'll compile it with donet build -p:APPIUM=true for APPIUM testing

OLD

Looks like the only simple solution is to isolate MyDep into a separate project and add it as reference on the main project, this way it will compile as a standalone dll with just the things I need to mock.

I then create another project which is a copy of the project that I want to mock and I modified the methods that I needed to mock.

NB. the output dll must compile with the same name of the original dll. In VS -> project properties -> Application -> Assembly name

I needed this to mock some code that communicates with hardware using appium for UI tests.

Before I start appium I compile the project into a test folder, and then replace the dll with the mock dll.