0

I have interface

public interface IActiveDirectoryService
{
   List<ActiveDirectoryUser> GetUsersInGroup(string group);
}

class (use interface)

public class ActiveDirectoryService : IActiveDirectoryService
{
   public List<ActiveDirectoryUser> GetUsersInGroup(string group){...}
}

fake class (inherit from original class, I override only some methods with new keyword)

public class ActiveDirectoryServiceFake : ActiveDirectoryService
{
   public new List<ActiveDirectoryUser> GetUsersInGroup(string group){...}
}

When I call fake service directly, the new method (which override/hide the original method) works.

var service = new ActiveDirectoryServiceFake();
var users = service.GetUsersInGroup(group);

but when I set this class into DI in Startup.cs

services.AddTransient<IActiveDirectoryService, ActiveDirectoryServiceFake>();

and I call _service.GetUsersInGroup(group), in visual studio I can see, that I have instance of ActiveDirectoryServiceFake but the original GetUsersInGroup method is called.

Why is that ?

Steven
  • 159,023
  • 23
  • 313
  • 420
Muflix
  • 5,120
  • 12
  • 65
  • 133

1 Answers1

2

Well, this is easy.

You have shadowed the method instead of overriding it (the difference: the new keyword does not override members, override does).

In your case, the correct code would be like this:

public class ActiveDirectoryService : IActiveDirectoryService
{
   public virtual List<ActiveDirectoryUser> GetUsersInGroup(string group){...}
}

public class ActiveDirectoryServiceFake : ActiveDirectoryService
{
   public override List<ActiveDirectoryUser> GetUsersInGroup(string group){...}
}
AgentFire
  • 8,501
  • 8
  • 41
  • 85
  • Exactly. Because it does not override the interface method, the call is not redirected to that class. There is no connection with that new method and the interface method. – juunas Apr 23 '20 at 08:37