#c# #asp.net-web-api #azure-cosmosdb
Вопрос:
Я использую ASP.NET Веб-Api 5.0 и CosmosDB.
Я могу использовать все свои сервисы внутри своего контроллера на изображении ниже
но у меня вся моя бизнес-логика находится внутри контроллера, а не в моих классах обслуживания, и я не могу использовать службы нигде, кроме как в своем контроллере.
Я хотел бы использовать службу снижения смертности внутри службы запуска соответствия, чтобы я мог выполнять всю свою бизнес-логику внутри службы запуска соответствия. Вот мой сервис Matchrun….
using Microsoft.Azure.Cosmos;
using ODSApi.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ODSApi.Services
{
public class MatchRunService : IMatchRunService
{
private Container _container;
public MatchRunService(
CosmosClient cosmosDbClient,
string databaseName,
string containerName
)
{
_container = cosmosDbClient.GetContainer(databaseName, containerName);
}
public async Task AddAsync(MatchRunEntity item)
{
await _container.CreateItemAsync(item, new PartitionKey(item.Id));
}
public async Task<MatchRunEntity> GetAsync(string id)
{
try
{
//get mortality slope by match id and sequence id
//
MortalitySlopeEntity mortalitySlope = await _container.ReadItemAsync<MortalitySlopeEntity>(id, new PartitionKey(id));
List<Dictionary<string, float>> mortalitySlopePoints = mortalitySlope.WaitListMortality;
MatchRunEntity MatchRun = await _container.ReadItemAsync<MatchRunEntity>(id, new PartitionKey(id));
MatchRun.PlotPoints = mortalitySlopePoints;
return MatchRun;
//return response.Resource;
}
catch (CosmosException) //For handling item not found and other exceptions
{
return null;
}
}
public async Task<IEnumerable<MatchRunEntity>> getByMatchSequence(string queryString)
{
var query = _container.GetItemQueryIterator<MatchRunEntity>(new QueryDefinition(queryString));
var results = new List<MatchRunEntity>();
while (query.HasMoreResults)
{
var response = await query.ReadNextAsync();
results.AddRange(response.ToList());
}
return results;
}
public async Task<IEnumerable<MatchRunEntity>> GetMultipleAsync(string queryString)
{
var query = _container.GetItemQueryIterator<MatchRunEntity>(new QueryDefinition(queryString));
var results = new List<MatchRunEntity>();
while (query.HasMoreResults)
{
var response = await query.ReadNextAsync();
results.AddRange(response.ToList());
}
return results;
}
}
}
Вот моя услуга по сбору смертных
using Microsoft.Azure.Cosmos;
using ODSApi.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ODSApi.Services
{
public class MortalitySlopeService : IMortalitySlopeService
{
private Container _container;
public MortalitySlopeService(
CosmosClient cosmosDbClient,
string databaseName,
string containerName)
{
_container = cosmosDbClient.GetContainer(databaseName, containerName);
}
public async Task AddAsync(MortalitySlopeEntity item)
{
await _container.CreateItemAsync(item, new PartitionKey(item.Id));
}
public async Task<MortalitySlopeEntity> GetAsync(string id)
{
try
{
//var response = _cosmosDbService.GetMultipleAsync("SELECT * FROM c")
var response = await _container.ReadItemAsync<MortalitySlopeEntity>(id, new PartitionKey(id));
return response.Resource;
}
catch (CosmosException) //For handling item not found and other exceptions
{
return null;
}
}
public async Task<IEnumerable<MortalitySlopeEntity>> GetMultipleAsync(string queryString)
{
var query = _container.GetItemQueryIterator<MortalitySlopeEntity>(new QueryDefinition(queryString));
var results = new List<MortalitySlopeEntity>();
while (query.HasMoreResults)
{
var response = await query.ReadNextAsync();
results.AddRange(response.ToList());
}
return results;
}
public async Task<IEnumerable<MortalitySlopeEntity>> getByMatchSequence(string queryString)
{
var query = _container.GetItemQueryIterator<MortalitySlopeEntity>(new QueryDefinition(queryString));
var results = new List<MortalitySlopeEntity>();
while (query.HasMoreResults)
{
var response = await query.ReadNextAsync();
results.AddRange(response.ToList());
}
return results;
}
//public MortalitySlopeEntity getOneByMatchSequence(int matchId, int sequenceId)
//{
// var slope = _container.GetItemLinqQueryable<MortalitySlopeEntity>(true)
// .Where(b => b.SequenceId == sequenceId amp;amp; b.MatchId == matchId)
// .AsEnumerable()
// .FirstOrDefault();
// return slope;
//}
}
}
Here is Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Identity.Web;
using Microsoft.OpenApi.Models;
using ODSApi.Services;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace ODSApi
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "ODSApi", Version = "v1" });
});
services.AddMicrosoftIdentityWebApiAuthentication(Configuration);
services.AddSingleton<ILogService>(InitializeCosmosClientInstanceAsyncLogs(Configuration.GetSection("CosmosDb")).GetAwaiter().GetResult());
services.AddSingleton<ITimeToNextOffer>(InitializeCosmosClientInstanceAsyncTimeToBetter(Configuration.GetSection("CosmosDb")).GetAwaiter().GetResult());
services.AddSingleton<IMatchRunService>(InitializeCosmosClientInstanceAsyncMatchRun(Configuration.GetSection("CosmosDb")).GetAwaiter().GetResult());
services.AddSingleton<IMortalitySlopeService>(InitializeCosmosClientInstanceAsyncMortalitySlope(Configuration.GetSection("CosmosDb")).GetAwaiter().GetResult());
services.AddApplicationInsightsTelemetry();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "ODSApi v1"));
}
app.UseSwagger();
app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "ODSApi v1"));
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
}
private static async Task<LogService> InitializeCosmosClientInstanceAsyncLogs(IConfigurationSection configurationSection)
{
var databaseName = configurationSection["DatabaseName"];
var containerName = configurationSection["ContainerName"];
var account = configurationSection["Account"];
var key = configurationSection["Key"];
var client = new Microsoft.Azure.Cosmos.CosmosClient(account, key);
var database = await client.CreateDatabaseIfNotExistsAsync(databaseName);
await database.Database.CreateContainerIfNotExistsAsync(containerName, "/id");
var cosmosDbService = new LogService(client, databaseName, containerName);
return cosmosDbService;
}
private static async Task<TimeToNextOffer> InitializeCosmosClientInstanceAsyncTimeToBetter(IConfigurationSection configurationSection)
{
var databaseName = configurationSection["DatabaseName"];
var containerName = "TimeToBetter";
var account = configurationSection["Account"];
var key = configurationSection["Key"];
var client = new Microsoft.Azure.Cosmos.CosmosClient(account, key);
var database = await client.CreateDatabaseIfNotExistsAsync(databaseName);
await database.Database.CreateContainerIfNotExistsAsync(containerName, "/id");
var cosmosDbService = new TimeToNextOffer(client, databaseName, containerName);
return cosmosDbService;
}
private static async Task<IMatchRunService> InitializeCosmosClientInstanceAsyncMatchRun(IConfigurationSection configurationSection)
{
var databaseName = configurationSection["DatabaseName"];
var containerName = "MatchRun";
var account = configurationSection["Account"];
var key = configurationSection["Key"];
var client = new Microsoft.Azure.Cosmos.CosmosClient(account, key);
var database = await client.CreateDatabaseIfNotExistsAsync(databaseName);
await database.Database.CreateContainerIfNotExistsAsync(containerName, "/id");
var cosmosDBService = new MatchRunService(client, databaseName, containerName);
return cosmosDBService;
}
private static async Task<IMortalitySlopeService> InitializeCosmosClientInstanceAsyncMortalitySlope(IConfigurationSection configurationSection)
{
var databaseName = configurationSection["DatabaseName"];
var containerName = "MortalitySlope";
var account = configurationSection["Account"];
var key = configurationSection["Key"];
var client = new Microsoft.Azure.Cosmos.CosmosClient(account, key);
var database = await client.CreateDatabaseIfNotExistsAsync(databaseName);
await database.Database.CreateContainerIfNotExistsAsync(containerName, "/id");
var cosmosDbService = new MortalitySlopeService(client, databaseName, containerName);
return cosmosDbService;
}
}
}
Every time I try to add the mortality slope service to the match run service I have problems with the constructors. I’m not sure how to do this, please help. Thanks.
Редактировать: Я думаю, что могу создать отдельную службу как таковую, но я не знаю, является ли это лучшим шаблоном с моей текущей конфигурацией.