Home > Software engineering >  DI using constructor not works because object required parameter less constructor
DI using constructor not works because object required parameter less constructor

Time:01-06

There is a class that uses some dependencies that will come from the constructor.

public class FooHttpApiHostModule : AbpModule
{
    private readonly ICustomContext _customContext;

    public FooHttpApiHostModule(ICustomContext customContext)
    {
        _customContext = customContext;
    }

    // Some other code here.
}

Inside the ApplicationModule, There is a scope added for it.

public class FooApplicationModule : AbpModule
{
    public override void ConfigureServices(ServiceConfigurationContext context)
    {
        context.Services
            .AddScoped<ICustomContext, CustomContext>();
    }
}

But when the code is running, next exception occur:

System.MissingMethodException: Cannot dynamically create an instance of type FooHttpApiHostModule.
Reason: No parameterless constructor defined.

The exception happens inside the Startup class on next line.

public class Startup
{
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddApplication<FooHttpApiHostModule>(); // <-- Exception on this line.
    }
}

Is there any other way to inject ICustomContext into FooHttpApiHostModule?


Update 1:

When writing this line in the ConfigureServices of my FooHttpApiHostModule

var graphContext = context.Services.GetRequiredService<ICustomContext>();

Next error occur

System.ArgumentNullException: Value cannot be null.
(Parameter provider)

Full code:

public class FooHttpApiHostModule : AbpModule
{
    // Removed constructor and private readonly variable.

    public override void ConfigureServices(ServiceConfigurationContext context)
    {
        ICustomContext customContext = context.Services.GetRequiredService<ICustomContext>(); // <-- exception on this line.
    }

    // Other code here...
}

Did an extra check and ICustomContext is added to the scope.

context.Services.IsAdded<ICustomContext>() == true

CodePudding user response:

You cannot use constructor injection like as you did for FooHttpApiHostModule.

Instead, you should use code like the below:

public class FooHttpApiHostModule : AbpModule
{

     public override void ConfigureServices(ServiceConfigurationContext context)
     {
        var customContext = context.Services.GetRequiredService<ICustomContext>()
        // customContext.Do();
        // Some other code here.
     }
}

Reference:

  1. https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-6.0#resolve-a-service-at-app-start-up
  •  Tags:  
  • Related