Currently working on a web services project for my class and have decided to make a web API using .NET Core and DynamodDB.
I was just curious what the best way to inject the DynamoDBContext
is?
I currently am doing it like this:
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDefaultAWSOptions(Configuration.GetAWSOptions());
services.AddAWSService<IAmazonDynamoDB>();
}
I got this piece of code above from the DynamoDB documentation. I add an instance of IAmazonDynamoDB
to the project.
DynamoDBContext context;
public ValuesController(IAmazonDynamoDB context)
{
this.context = new DynamoDBContext(context);
}
In the controller, I then inject the IAmazonDynamoDB
instance, and use that to create an instance of DynamoDBContext
.
Is there a way to create an instance of the context in the ConfigureServices
method and add it to the project there, or is the way I am doing it currently fine?
Is there a way to create an instance of the context in the ConfigureServices method and add it to the project there, or is the way I am doing it currently fine?
Although your solution will work, it has a drawback. You're not using Dependency Injection for DynamoDBContext
and create its instance in controller constructor through new
operator. You'll face a problems when it comes to unit testing your code, because you have no way to substitute implementation of DynamoDBContext
.
The proper way is to register DynamoDBContext
in DI container and let the container itself create an instance when it's required. With such approach IDynamoDBContext
gets injected into ValuesController
:
public class ValuesController
{
private readonly IDynamoDBContext context;
public ValuesController(IDynamoDBContext context)
{
this.context = context;
}
// ...
}
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
services.AddDefaultAWSOptions(Configuration.GetAWSOptions());
services.AddAWSService<IAmazonDynamoDB>();
services.AddTransient<IDynamoDBContext, DynamoDBContext>();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With