简体   繁体   中英

.Net Core service is not getting registered

I have the following two classes with interface

public interface IInterface1
{
 //declarations
}

public class class1 : IInterface1
{
 //definitions
}

public interface IInterface2
{
//declarations
}

public class class2 : IInterface2
{
   private readonly IInterface1 _interface;
   //constructor
   public class2(IInterface1 interface1)
   {
     //getting null for interface1
     _interface = interface1;
   }
}

and a controller where i'm injecting the IInterface2

public class MyController : Controller
{
  private readonly IInterface2 _usecase;
  public MyController(IInterface2 usecase)
  {
    _usecase = usecase;
  }
}

and in Startup.cs i have registered service like this

public void ConfigureServices(IServiceCollection services)
{
  services.AddScoped<IInterface2, class2>();
  services.AddScoped<IInterface1, class1>(x => (class1)x.GetService<IInterface1>());
}

the issue which facing is when i'm injecting the IInterface1 in class2 not able to access the properties of the interface1 in constructor instead getting null

The example you showed in the question works well if you replace the configuration with this :

public void ConfigureServices(IServiceCollection services)
{
  services.AddScoped<IInterface2, class2>();
  services.AddScoped<IInterface1, class1>();
}

Note that the line you wrote :

services.AddScoped<IInterface1, class1>(x => (class1)x.GetService<IInterface1>())

is causing Access Violation

(Because, when Interface1 is needed, dependency system will try to get ... an Interface1 from the dependency system using GetService , executing this rule in an infinite recursion)

We need more details to understand your problem and help solving it.

You may need to create a factory for your classes, or solve the circular dependency you mentionned in comments, that apparently prevents you from using the simple injection shown here.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM