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 typeFooHttpApiHostModule.
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.
(Parameterprovider)
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.
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:

