Inject MongoClient as a dependency in FeedbackReceiverService.

This commit is contained in:
Denis-Cosmin Nutiu 2021-05-30 21:16:01 +03:00
parent 7daa314ad1
commit bb23e6193e
4 changed files with 21 additions and 6 deletions

View file

@ -0,0 +1,6 @@
namespace Retroactiune.Tests.Retroactiune.WebAPI.Services
{
public class TestFeedbackReceiverService
{
}
}

View file

@ -1,7 +1,6 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.Extensions.Logging;
using MongoDB.Driver;
using Retroactiune.Models;
using Retroactiune.Settings;
@ -15,14 +14,11 @@ namespace Retroactiune.Services
public class FeedbackReceiverService : IFeedbackReceiverService
{
private readonly IMongoCollection<FeedbackReceiver> _collection;
private readonly ILogger<FeedbackReceiverService> _logger;
public FeedbackReceiverService(IMongoDbSettings settings, ILogger<FeedbackReceiverService> logger)
public FeedbackReceiverService(IMongoClient client, IMongoDbSettings settings)
{
var client = new MongoClient(settings.ConnectionString);
var database = client.GetDatabase(settings.DatabaseName);
_collection = database.GetCollection<FeedbackReceiver>(settings.FeedbackReceiverCollectionName);
_logger = logger;
}
public async Task CreateManyAsync(IEnumerable<FeedbackReceiver> items)

View file

@ -6,6 +6,7 @@ using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using MongoDB.Driver;
using Retroactiune.Services;
using Retroactiune.Settings;
@ -28,11 +29,17 @@ namespace Retroactiune
services.AddSingleton<IMongoDbSettings>(sp =>
sp.GetRequiredService<IOptions<RetroactiuneDbSettings>>().Value);
// AutoMapper
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
// Services
services.AddSingleton<IFeedbackReceiverService, FeedbackReceiverService>();
services.AddSingleton<IMongoClient, MongoClient>(i =>
{
var settings = i.GetService<IOptions<RetroactiuneDbSettings>>();
return new MongoClient(settings.Value.ConnectionString);
});
// WebAPI
services.AddControllers();

View file

@ -3,6 +3,7 @@ using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using MongoDB.Driver;
using Retroactiune.Services;
using Retroactiune.Settings;
@ -33,6 +34,11 @@ namespace Retroactiune
// Services
services.AddSingleton<IFeedbackReceiverService, FeedbackReceiverService>();
services.AddSingleton<IMongoClient, MongoClient>(i =>
{
var settings = i.GetService<IOptions<RetroactiuneDbSettings>>();
return new MongoClient(settings.Value.ConnectionString);
});
// WebAPI
services.AddControllers();