Skip to content

Commit

Permalink
Refactoring: MultiBankProviderFactory & MultiBankProviderBuilder.
Browse files Browse the repository at this point in the history
  • Loading branch information
o.nadymov committed Mar 29, 2024
1 parent 20de1b0 commit 9ae6a7d
Show file tree
Hide file tree
Showing 19 changed files with 364 additions and 180 deletions.
56 changes: 49 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ The project for integration with MultiBank host.

## Быстрый старт

Клиент написан на C#, .NET 7.0 с использованием Dependency Injection от [Microsoft](https://docs.microsoft.com/en-us/dotnet/core/extensions/dependency-injection-usage).
Клиент написан на C# .NET 7.0, .NET 8.0

### Установка Nuget пакета:
Для использования этого SDK необходимо установить Nuget пакет ``Spoleto.VirtualKassa.MultiBank``:
Expand All @@ -20,26 +20,68 @@ https://www.nuget.org/packages/Spoleto.VirtualKassa.MultiBank
Install-Package Spoleto.VirtualKassa.MultiBank -ProjectName StoreApplication
```

### Определение зависимостей
### MultiBankProvider
Для создания экземпляра ``MultiBankProvider`` рекомендуется использовать ``Spoleto.VirtualKassa.MultiBank.MultiBankProviderFactory``:
```
var factory = new MultiBankProviderFactory();
var provider = factory.Build();
// Либо с передачей экземпляра HttpClient:
var httpClient = new HttpClient();
var factory = new MultiBankProviderFactory()
.WithHttpClient(httpClient);
var provider = factory.Build();
```

### Dependency Injection
Чтобы интегрировать ``Spoleto.VirtualKassa.MultiBank`` в Microsoft Dependency injection следует использовать NuGet пакет [**Spoleto.VirtualKassa.MultiBank.Extensions**](https://www.nuget.org/packages/Spoleto.VirtualKassa.MultiBank.Extensions/). Этот пакет предоставляет методы-расширения для интерфейса ``IServiceCollection``, которые регистрируют ``MultiBankProvider`` как transient сервис.

```csharp
using Microsoft.Extensions.DependencyInjection;
using Spoleto.VirtualKassa.MultiBank.Extensions;
using Spoleto.VirtualKassa.MultiBank.Models;
using Spoleto.VirtualKassa.MultiBank.Providers;

// Set up the dependency injection container
var services = new ServiceCollection();
var services = new ServiceCollection();

// Register your dependencies here.
services.AddHttpClient();
services.AddSingleton<IMultiBankProvider, MultiBankProvider>();
services.AddMultiBank();

// Build the service provider
var serviceProvider = services.BuildServiceProvider();
```

### Внедрение службы MultiBankProvider в ваши классы
После регистрации ``Spoleto.VirtualKassa.MultiBank`` в вашем фреймворке Dependency Injection вы можете внедрить ``MultiBankProvider`` в любой класс вашего приложения.

Для этого внедрите интерфейс ``IMultiBankProvider`` в конструкторы классов, в которых вы хотите использовать функциональность ``MultiBankProvider``:

```csharp
public class YourMultiBankClass
{
private readonly ILogger<YourMultiBankClass> _logger;
private readonly IMultiBankProvider _multiBankProvider;

public YourMultiBankClass(ILogger<YourMultiBankClass> logger, IMultiBankProvider multiBankProvider)
{
_logger = logger;
_multiBankProvider = multiBankProvider;
}

public async Task Sell(SaleSlip slip)
{
var result = await _multiBankProvider.SellAsync(_settings, saleSlip);

// log the result:
_logger.LogInformation("Sold {slip} with result: {result}", slip, result);
}
}
```
```
### Вызов методов API
### Примеры вызовов методов API
#### Открытие смены
```csharp
var settings = new MultiBankOption { ServiceUrl = "http://localhost:8080/" };
Expand Down
10 changes: 9 additions & 1 deletion Spoleto.VirtualKassa.MultiBank.sln
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{5AA9A2B7-BD1B-4484-919E-AC10F1616B0D}"
ProjectSection(SolutionItems) = preProject
src\.editorconfig = src\.editorconfig
src\Directory.Build.props = src\Directory.Build.props
LICENSE = LICENSE
README.md = README.md
EndProjectSection
Expand All @@ -18,10 +19,13 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Spoleto.VirtualKassa.MultiB
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "WorkFlow", "WorkFlow", "{48E65D95-265B-44DB-A560-CCE813F25732}"
ProjectSection(SolutionItems) = preProject
.github\workflows\cd.yml = .github\workflows\cd.yml
.github\workflows\ci.yml = .github\workflows\ci.yml
publish-assets-to-github.sh = publish-assets-to-github.sh
.github\workflows\publish-to-nuget.yml = .github\workflows\publish-to-nuget.yml
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spoleto.VirtualKassa.MultiBank.Extensions", "src\Spoleto.VirtualKassa.MultiBank.Extensions\Spoleto.VirtualKassa.MultiBank.Extensions.csproj", "{CF851703-0DB0-47D5-A706-A3DF0398FEAB}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Expand All @@ -40,6 +44,10 @@ Global
{B36D9DEF-7960-42FA-9188-EAFBBEE77C51}.Debug|Any CPU.Build.0 = Debug|Any CPU
{B36D9DEF-7960-42FA-9188-EAFBBEE77C51}.Release|Any CPU.ActiveCfg = Release|Any CPU
{B36D9DEF-7960-42FA-9188-EAFBBEE77C51}.Release|Any CPU.Build.0 = Release|Any CPU
{CF851703-0DB0-47D5-A706-A3DF0398FEAB}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{CF851703-0DB0-47D5-A706-A3DF0398FEAB}.Debug|Any CPU.Build.0 = Debug|Any CPU
{CF851703-0DB0-47D5-A706-A3DF0398FEAB}.Release|Any CPU.ActiveCfg = Release|Any CPU
{CF851703-0DB0-47D5-A706-A3DF0398FEAB}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
Expand Down
File renamed without changes
70 changes: 70 additions & 0 deletions src/Directory.Build.props
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
<Project>

<PropertyGroup>
<LangVersion>latest</LangVersion>
</PropertyGroup>

<!-- Include symbols for debugging -->
<PropertyGroup>
<!-- This command creates external file (snupkg) with .pdb next to nuget file (nupkg) -->
<IncludeSymbols>true</IncludeSymbols>
<SymbolPackageFormat>snupkg</SymbolPackageFormat>
</PropertyGroup>

<!-- https://github.com/dotnet/sourcelink -->
<PropertyGroup>
<!-- Optional: Publish the repository URL in the built .nupkg (in the NuSpec <Repository> element) -->
<PublishRepositoryUrl>true</PublishRepositoryUrl>

<!-- Optional: Embed source files that are not tracked by the source control manager in the PDB -->
<EmbedUntrackedSources>true</EmbedUntrackedSources>
</PropertyGroup>

<!-- Package info -->
<PropertyGroup>
<Product>Spoleto.VirtualKassa.MultiBank library</Product>
<Authors>OlegNadymov;Spoleto-Software</Authors>
<Company>SPOLETO Software Development</Company>
<PackageIcon>MainIcon.jpg</PackageIcon>
<PackageProjectUrl>https://spoleto.ru</PackageProjectUrl>
<RepositoryUrl>https://github.com/spoleto-software/Spoleto.VirtualKassa.MultiBank</RepositoryUrl>
<RepositoryType>GitHub</RepositoryType>
<PackageReadmeFile>README.md</PackageReadmeFile>
<PackageLicenseFile>LICENSE</PackageLicenseFile>
<PackageRequireLicenseAcceptance>true</PackageRequireLicenseAcceptance>
<PackageTags>МультиКасса; МультиБанк; ВиртуальнаяКасса; VirtualKassa; MultiBank; Multikassa</PackageTags>
<Copyright>Copyright © $([System.DateTime]::Now.Year.ToString())</Copyright>
<PackageReleaseNotes></PackageReleaseNotes>
<Version>1.13.0</Version>
<AssemblyVersion>1.13.0.0</AssemblyVersion>
<FileVersion>1.13.0.0</FileVersion>
</PropertyGroup>

<PropertyGroup Condition="'$(Configuration)' == 'Release'">
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>$(NoWarn);CS1591</NoWarn>
</PropertyGroup>

<ItemGroup>
<None Include="$(MSBuildThisFileDirectory)..\LICENSE">
<Pack>True</Pack>
<PackagePath>\</PackagePath>
<Visible>False</Visible>
</None>
<None Include="$(MSBuildThisFileDirectory)..\README.md">
<Pack>True</Pack>
<PackagePath>\</PackagePath>
<Visible>False</Visible>
</None>
<None Include="$(MSBuildThisFileDirectory)..\assets\MainIcon.jpg">
<Pack>True</Pack>
<PackagePath></PackagePath>
<Visible>False</Visible>
</None>
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.SourceLink.GitHub" Version="8.0.0" PrivateAssets="All"/>
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
using Microsoft.Extensions.DependencyInjection;

namespace Spoleto.VirtualKassa.MultiBank.Extensions
{
/// <summary>
/// Spoleto.VirtualKassa.MultiBank dependency injection builder.
/// </summary>
public class MultiBankProviderBuilder
{
/// <summary>
/// Creates an instance of <see cref="MultiBankProviderBuilder"/>.
/// </summary>
/// <param name="serviceCollection">The services collection instance.</param>
internal MultiBankProviderBuilder(IServiceCollection serviceCollection)
{
ServiceCollection = serviceCollection;
}

/// <summary>
/// Gets the service collection.
/// </summary>
public IServiceCollection ServiceCollection { get; }
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using Microsoft.Extensions.DependencyInjection;

namespace Spoleto.VirtualKassa.MultiBank.Extensions
{
/// <summary>
/// Extension methods to configure an <see cref="IServiceCollection"/> for <see cref="IMultiBankProvider"/>.
/// </summary>
public static class ServiceCollectionExtensions
{
/// <summary>
/// Adds the Spoleto.VirtualKassa.MultiBank provider.
/// </summary>
/// <param name="serviceCollection">The service collection instance.</param>
/// <returns>The <see cref="SmsServiceBuilder"/> instance is provided to support method chaining capabilities.</returns>
public static MultiBankProviderBuilder AddMultiBank(this IServiceCollection serviceCollection)
{
serviceCollection.AddHttpClient<IMultiBankProvider, MultiBankProvider>();

// registers the providers on this instance:
return new MultiBankProviderBuilder(serviceCollection);
}

/// <summary>
/// Adds the Spoleto.VirtualKassa.MultiBank provider with the specified instance of <see cref="HttpClient"/>.
/// </summary>
/// <param name="serviceCollection">The service collection instance.</param>
/// <param name="httpClient">The <see cref="HttpClient"/> instance.</param>
/// <returns>The <see cref="SmsServiceBuilder"/> instance is provided to support method chaining capabilities.</returns>
public static MultiBankProviderBuilder AddMultiBank(this IServiceCollection serviceCollection, HttpClient httpClient)
{
serviceCollection.AddTransient<IMultiBankProvider>(x => new MultiBankProvider(httpClient));

// registers the providers on this instance:
return new MultiBankProviderBuilder(serviceCollection);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFrameworks>net7.0;net8.0</TargetFrameworks>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<!-- Package info -->
<PropertyGroup>
<Title>Spoleto.VirtualKassa.MultiBank extensions for Microsoft DependencyInjection</Title>
<PackageId>Spoleto.VirtualKassa.MultiBank.Extensions</PackageId>
<PackageTags>МультиКасса; МультиБанк; ВиртуальнаяКасса; VirtualKassa; MultiBank; Multikassa</PackageTags>
<Description>
Расширения для работы с Microsoft Dependency injection фреймворком для C# SDK для интеграции с хостом Мульти-Банка (Узбекистан) для передачи информации об оплатах покупок.
The extensions for Microsoft Dependency injection framework for the project for integration with MultiBank host.
</Description>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="8.0.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Spoleto.VirtualKassa.MultiBank\Spoleto.VirtualKassa.MultiBank.csproj" />
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
namespace Spoleto.VirtualKassa.MultiBank.Tests
{
public class MultiBankProviderFactoryTests
{
[Test]
public async Task CreateMultiBankProvider()
{
// Arrange
var factory = new MultiBankProviderFactory();

// Act
var provider = factory.Build();

// Assert
Assert.That(provider, Is.Not.Null);
}

[Test]
public async Task CreateMultiBankProviderWithHttpClient()
{
// Arrange
var httpClient = new HttpClient();
var factory = new MultiBankProviderFactory()
.WithHttpClient(httpClient);

// Act
var provider = factory.Build();

// Assert
Assert.That(provider, Is.Not.Null);
}
}
}
6 changes: 2 additions & 4 deletions src/Spoleto.VirtualKassa.MultiBank.Tests/MultiBankTests.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
using Microsoft.Extensions.DependencyInjection;
using Spoleto.Common.Helpers;
using Spoleto.VirtualKassa.MultiBank.Extensions;
using Spoleto.VirtualKassa.MultiBank.Models;
using Spoleto.VirtualKassa.MultiBank.Providers;

namespace Spoleto.VirtualKassa.MultiBank.Tests
{
Expand All @@ -14,8 +13,7 @@ public class MultiBankTests
public void OneTimeSetUp()
{
var services = new ServiceCollection();
services.AddHttpClient();
services.AddSingleton<IMultiBankProvider, MultiBankProvider>();
services.AddMultiBank();

_serviceProvider = services.BuildServiceProvider();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,26 +21,27 @@
</ItemGroup>

<ItemGroup>
<PackageReference Include="Microsoft.Extensions.Configuration" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="7.0.4" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="7.0.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="7.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.7.2" />
<PackageReference Include="NUnit" Version="3.13.3" />
<PackageReference Include="Microsoft.Extensions.Configuration" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Binder" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Configuration.UserSecrets" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.DependencyInjection" Version="8.0.0" />
<PackageReference Include="Microsoft.Extensions.Http" Version="8.0.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.9.0" />
<PackageReference Include="NUnit" Version="4.1.0" />
<PackageReference Include="NUnit3TestAdapter" Version="4.5.0" />
<PackageReference Include="NUnit.Analyzers" Version="3.8.0">
<PackageReference Include="NUnit.Analyzers" Version="4.1.0">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="coverlet.collector" Version="6.0.0">
<PackageReference Include="coverlet.collector" Version="6.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\Spoleto.VirtualKassa.MultiBank.Extensions\Spoleto.VirtualKassa.MultiBank.Extensions.csproj" />
<ProjectReference Include="..\Spoleto.VirtualKassa.MultiBank\Spoleto.VirtualKassa.MultiBank.csproj" />
</ItemGroup>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
using Microsoft.Extensions.DependencyInjection;
using Spoleto.Common.Helpers;
using Spoleto.VirtualKassa.MultiBank.Models;
using Spoleto.VirtualKassa.MultiBank.Providers;
using Spoleto.VirtualKassa.MultiBank;
using Spoleto.VirtualKassa.MultiBank.Tests;
using Spoleto.VirtualKassa.MultiBank.Extensions;

namespace Spoleto.VirtualKassa.MultiBank.WpfTester
{
Expand All @@ -24,8 +25,7 @@ public MainWindow()
var services = new ServiceCollection();

// Register your dependencies here.
services.AddHttpClient();
services.AddSingleton<IMultiBankProvider, MultiBankProvider>();
services.AddMultiBank();

// Build the service provider
_serviceProvider = services.BuildServiceProvider();
Expand Down
Loading

0 comments on commit 9ae6a7d

Please sign in to comment.