Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Register unity without config file #286

Open
wants to merge 14 commits into
base: feature-239-use-proper-di
Choose a base branch
from
142 changes: 105 additions & 37 deletions Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/App.config
Original file line number Diff line number Diff line change
Expand Up @@ -16,43 +16,111 @@
<add key="ClientSettingsProvider.ServiceUri" value="" />
</appSettings>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<alias alias="singleton" type="Unity.Lifetime.ContainerControlledLifetimeManager, Unity.Abstractions" />
<container>
<register type="ICSSoft.STORMNET.Business.Audit.IAuditService, ICSSoft.STORMNET.Business" mapTo="ICSSoft.STORMNET.Business.Audit.AuditService, ICSSoft.STORMNET.Business">
<lifetime type="singleton" />
</register>
<!-- Для использования экспорта нужно установить пакет NewPlatform.Flexberry.Reports.ExportToExcel -->
<!--
<register name="Export" type="NewPlatform.Flexberry.IExportService, ICSSoft.STORMNET.Business" mapTo="NewPlatform.Flexberry.Reports.ExportToExcel.ExportExcelODataService, NewPlatform.Flexberry.Reports.ExportToExcel">
<lifetime type="singleton" />
</register>
-->
<register type="NewPlatform.Flexberry.IODataExportService, ICSSoft.STORMNET.Business" mapTo="NewPlatform.Flexberry.ORM.ODataService.Tests.CRUD.Read.Excel.ExportExcel,NewPlatform.Flexberry.ORM.ODataService.Tests">
<lifetime type="singleton" />
</register>
<!--
<register type="NewPlatform.Flexberry.Reports.ExportToExcel.ISpreadsheetCustomizer, NewPlatform.Flexberry.Reports.ExportToExcel" mapTo="NewPlatform.Flexberry.ORM.ODataService.Tests.CRUD.Read.SpreadsheetCustomizer,NewPlatform.Flexberry.ORM.ODataService.Tests">
<lifetime type="singleton" />
</register>
-->
<register type="ICSSoft.STORMNET.Business.IConfigResolver, ICSSoft.STORMNET.Business" mapTo="ICSSoft.STORMNET.Business.ConfigResolver, ICSSoft.STORMNET.Business">
<lifetime type="singleton" />
<constructor />
</register>

<register type="NewPlatform.Flexberry.Caching.ICacheService, NewPlatform.Flexberry.Caching" mapTo="NewPlatform.Flexberry.Caching.MemoryCacheService, NewPlatform.Flexberry.Caching">
<lifetime type="singleton" />
<constructor>
<param name="cacheName" type="System.String" value="defaultCacheForApplication" />
<param name="defaultExpirationTime" type="System.Int32" value="3600" />
</constructor>
</register>

<register type="NewPlatform.Flexberry.Security.IPasswordHasher, NewPlatform.Flexberry.Security" mapTo="NewPlatform.Flexberry.Security.Sha1PasswordHasher, NewPlatform.Flexberry.Security">
<lifetime type="singleton" />
<constructor />
</register>
</container>
<alias alias="singleton" type="Unity.Lifetime.ContainerControlledLifetimeManager, Unity.Abstractions" />
<container>
<register type="ICSSoft.STORMNET.Business.Audit.IAuditService, ICSSoft.STORMNET.Business" mapTo="ICSSoft.STORMNET.Business.Audit.AuditService, ICSSoft.STORMNET.Business" />
<!-- Для использования экспорта нужно установить пакет NewPlatform.Flexberry.Reports.ExportToExcel -->
<!--
<register name="Export" type="NewPlatform.Flexberry.IExportService, ICSSoft.STORMNET.Business" mapTo="NewPlatform.Flexberry.Reports.ExportToExcel.ExportExcelODataService, NewPlatform.Flexberry.Reports.ExportToExcel">
<lifetime type="singleton" />
</register>
-->
<register type="NewPlatform.Flexberry.IODataExportService, ICSSoft.STORMNET.Business" mapTo="NewPlatform.Flexberry.ORM.ODataService.Tests.CRUD.Read.Excel.ExportExcel,NewPlatform.Flexberry.ORM.ODataService.Tests">
<lifetime type="singleton" />
</register>
<!--
<register type="NewPlatform.Flexberry.Reports.ExportToExcel.ISpreadsheetCustomizer, NewPlatform.Flexberry.Reports.ExportToExcel" mapTo="NewPlatform.Flexberry.ORM.ODataService.Tests.CRUD.Read.Excel.SpreadsheetCustomizer,NewPlatform.Flexberry.ORM.ODataService.Tests">
<lifetime type="singleton" />
</register>
-->
<register type="ICSSoft.STORMNET.Business.IConfigResolver, ICSSoft.STORMNET.Business" mapTo="ICSSoft.STORMNET.Business.ConfigResolver, ICSSoft.STORMNET.Business">
<lifetime type="singleton" />
<constructor />
</register>
<register type="NewPlatform.Flexberry.Caching.ICacheService, NewPlatform.Flexberry.Caching" mapTo="NewPlatform.Flexberry.Caching.MemoryCacheService, NewPlatform.Flexberry.Caching">
<lifetime type="singleton" />
<constructor>
<param name="cacheName" type="System.String" value="defaultCacheForApplication" />
<param name="defaultExpirationTime" type="System.Int32" value="3600" />
</constructor>
</register>
<register name="dataServiceForAuditAgentManagerAdapter" type="ICSSoft.STORMNET.Business.IDataService, ICSSoft.STORMNET.Business" mapTo="ICSSoft.STORMNET.Business.MSSQLDataService, ICSSoft.STORMNET.Business.MSSQLDataService">
<constructor>
<param name="securityManager" type="ICSSoft.STORMNET.Security.ISecurityManager, ICSSoft.STORMNET.DataObject">
<dependency name="securityManagerWithoutRightsCheck" />
</param>
<param name="auditService" type="ICSSoft.STORMNET.Business.Audit.IAuditService, ICSSoft.STORMNET.Business">
<dependency />
</param>
<param name="businessServerProvider" type="ICSSoft.STORMNET.Business.Interfaces.IBusinessServerProvider, ICSSoft.STORMNET.Business">
<dependency />
Copy link
Contributor

@Anisimova2020 Anisimova2020 Jun 26, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Мне вот эта регистрация очень интересна, проходит ли корректно. Можешь убрать все регистрации в коде, потом сделать получение dataServiceForAuditAgentManagerAdapter. Мне очень интересно, как оно разрешает конструктор "BusinessServerProvider(IServiceProvider serviceProvider)". Нужно под дебагом посмотреть, инициализируется ли приватное свойство "serviceProvider".

Дело в том, что регистрация "unityContainer.RegisterFactory(new Func<IUnityContainer, object>(o => new BusinessServerProvider(new UnityServiceProvider(o))), FactoryLifetime.Singleton);" была наверчена от того, что конфиг в теории не должен был дать это нормально разрешить. Соответственно, если это работает, то круто, об этом нужно сообщить мне, я включу в свои документы. Если это не работает, а срабатывало только от того, что юнити так сильно не проверяло, то нужно оставить в конфиге только работающее.
Либо возможно работает, потому что сейчас в коде фабрика дорегистрируется IBusinessServerProvider как фабрика. Это тоже хороший вариант, о котором нужно мне сказать.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

done

</param>
</constructor>
<property name="CustomizationStringName" dependencyType="System.String" value="DefConnStr" />
</register>
<register name="dataServiceForSecurityManager" type="ICSSoft.STORMNET.Business.IDataService, ICSSoft.STORMNET.Business" mapTo="ICSSoft.STORMNET.Business.MSSQLDataService, ICSSoft.STORMNET.Business.MSSQLDataService">
<constructor>
<param name="securityManager" type="ICSSoft.STORMNET.Security.ISecurityManager, ICSSoft.STORMNET.DataObject">
<dependency name="securityManagerWithoutRightsCheck" />
</param>
<param name="auditService" type="ICSSoft.STORMNET.Business.Audit.IAuditService, ICSSoft.STORMNET.Business">
<dependency />
</param>
<param name="businessServerProvider" type="ICSSoft.STORMNET.Business.Interfaces.IBusinessServerProvider, ICSSoft.STORMNET.Business">
<dependency />
</param>
</constructor>
<property name="CustomizationStringName" dependencyType="System.String" value="DefConnStr" />
</register>
<register name="cacheServiceForSecurityManager" type="NewPlatform.Flexberry.Caching.ICacheService, NewPlatform.Flexberry.Caching" mapTo="NewPlatform.Flexberry.Caching.MemoryCacheService, NewPlatform.Flexberry.Caching">
<lifetime type="singleton" />
<constructor>
<param name="cacheName" type="System.String" value="cacheForSecurityManager" />
</constructor>
</register>
<register name="cacheServiceForAgentManager" type="NewPlatform.Flexberry.Caching.ICacheService, NewPlatform.Flexberry.Caching" mapTo="NewPlatform.Flexberry.Caching.MemoryCacheService, NewPlatform.Flexberry.Caching">
<lifetime type="singleton" />
<constructor>
<param name="cacheName" type="System.String" value="cacheForAgentManager" />
</constructor>
</register>
<register type="ICSSoft.STORMNET.Security.ISecurityManager, ICSSoft.STORMNET.DataObject" mapTo="NewPlatform.Flexberry.Security.SecurityManager, NewPlatform.Flexberry.Security">
<constructor>
<param name="dataService" type="ICSSoft.STORMNET.Business.IDataService, ICSSoft.STORMNET.Business">
<dependency name="dataServiceForSecurityManager" />
</param>
<param name="cacheService" type="NewPlatform.Flexberry.Caching.ICacheService, NewPlatform.Flexberry.Caching">
<dependency name="cacheServiceForSecurityManager" />
</param>
<param name="enabled" type="System.Boolean" value="true" />
<param name="useRightsOnObjects" type="System.Boolean" value="false" />
<param name="useRightsOnAttribute" type="System.Boolean" value="false" />
</constructor>
</register>
<register type="NewPlatform.Flexberry.Security.IAgentManager, NewPlatform.Flexberry.Security" mapTo="NewPlatform.Flexberry.Security.AgentManager, NewPlatform.Flexberry.Security">
<constructor>
<param name="dataService" type="ICSSoft.STORMNET.Business.IDataService, ICSSoft.STORMNET.Business">
<dependency name="dataServiceForSecurityManager" />
</param>
<param name="cacheService" type="NewPlatform.Flexberry.Caching.ICacheService, NewPlatform.Flexberry.Caching">
<dependency name="cacheServiceForAgentManager" />
</param>
</constructor>
</register>
<register type="NewPlatform.Flexberry.Security.IPasswordHasher, NewPlatform.Flexberry.Security" mapTo="NewPlatform.Flexberry.Security.Sha1PasswordHasher, NewPlatform.Flexberry.Security">
<lifetime type="singleton" />
<constructor />
</register>
<register name="securityManagerWithoutRightsCheck" type="ICSSoft.STORMNET.Security.ISecurityManager, ICSSoft.STORMNET.DataObject" mapTo="ICSSoft.STORMNET.Security.EmptySecurityManager, ICSSoft.STORMNET.DataObject">
<lifetime type="singleton" />
<constructor />
</register>
<register type="System.IFormatProvider" mapTo="System.Globalization.CultureInfo" >
<constructor>
<param name="name" value="da-DK" />
</constructor>
</register>
</container>
</unity>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
using System;

using Unity;

namespace NewPlatform.Flexberry.ORM.ODataService.Tests
{
using System;
using Unity;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Для чего здесь юзинги добавлены?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed


/// <summary>
/// Specifies the Unity configuration for the main container.
/// </summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ namespace NewPlatform.Flexberry.ORM.ODataService.Tests
using ICSSoft.STORMNET.Business;
using ICSSoft.STORMNET.Business.Audit;
using ICSSoft.STORMNET.Business.Interfaces;
using ICSSoft.STORMNET.Security;
using ICSSoft.STORMNET.Security;
using Microsoft.Practices.Unity.Configuration;
using Moq;
using Npgsql;
using Oracle.ManagedDataAccess.Client;
Expand All @@ -27,7 +28,7 @@ namespace NewPlatform.Flexberry.ORM.ODataService.Tests
public abstract class BaseIntegratedTest : IDisposable
{
#endif
#if NETCOREAPP
#if NETCOREAPP
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Practices.Unity.Configuration;
using ODataServiceSample.AspNetCore;
Expand Down Expand Up @@ -159,12 +160,9 @@ protected BaseIntegratedTest(CustomWebApplicationFactory<Startup> factory, ITest
_factory = factory;
#endif

_container = new UnityContainer();
#if NETCOREAPP
_container.LoadConfiguration();
#endif
_container = new UnityContainer();
_serviceProvider = new UnityServiceProvider(_container);
_container.RegisterFactory<IBusinessServerProvider>(new Func<IUnityContainer, object>(o => new BusinessServerProvider(new UnityServiceProvider(o))), FactoryLifetime.Singleton);
UnityContainerRegistrations.BSProviderRegistration(_container);
businessServerProvider = _container.Resolve<IBusinessServerProvider>();
#if NETCOREAPP
CustomWebApplicationFactory<Startup>._unityContainer = _container;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,12 @@
#if NETFRAMEWORK
using System.Web.Http;
using System.Web.Http.Cors;
using ICSSoft.Services;
using ICSSoft.STORMNET.Business.Interfaces;
using NewPlatform.Flexberry.ORM.ODataService.Extensions;
using NewPlatform.Flexberry.ORM.ODataService.WebApi.Extensions;
using Unity.AspNet.WebApi;
using Microsoft.Practices.Unity.Configuration;
#endif
#if NETCOREAPP
using NewPlatform.Flexberry.ORM.ODataService.Routing;
Expand Down Expand Up @@ -131,6 +134,12 @@ public virtual void ActODataService(Action<TestArgs> action)
using (HttpServer server = new HttpServer(config))
using (HttpClient client = new HttpClient(server, false) { BaseAddress = new Uri("http://localhost/odata/") })
{
UnityContainerRegistrations.BSProviderRegistration(container);

container.LoadConfiguration();
// Base dependencies registration (Uncomment if you want to use code instead of config for registrations)
UnityContainerRegistrations.Registration(container);

container.RegisterType<DataObjectEdmModelDependencies>(
new InjectionConstructor(
container.IsRegistered<IExportService>() ? container.Resolve<IExportService>() : null,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
namespace NewPlatform.Flexberry.ORM.ODataService.Tests
{
using System;
using System.Collections;
using System.Configuration;
using System.Globalization;
using System.Linq;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

После System-юзингов желательно пустую строчку.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed


using Microsoft.Practices.Unity.Configuration;
using Unity;
using Unity.Injection;
using Xunit;

/// <summary>
/// Class for checking that a dependency registered in the code can be overriden from the config.
/// </summary>
public class CheckLoadConfigurationTest
Copy link
Contributor

@Anisimova2020 Anisimova2020 Jun 26, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нужны комментарии к классу тестов.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed

{
[Fact]
public void CheckIfLoadConfigurationWorks()
{
using var container = new UnityContainer();

// Default culture
container.RegisterType<IFormatProvider, CultureInfo>(
new InjectionConstructor("en-US"));

// This type is registered in code only. Just to prove its registration survives.
container.RegisterType<IList, ArrayList>();

Assert.Equal("$1,234.56", GetFormattedSum(container.Resolve<IFormatProvider>(), 1234.56M));
string beforeLoad = GetCodeRegistration(container);

// Override with the config file
if (ConfigurationManager.GetSection("unity") != null)
{
container.LoadConfiguration();
Assert.Equal("1.234,56 kr.", GetFormattedSum(container.Resolve<IFormatProvider>(), 1234.56M));

string afterLoad = GetCodeRegistration(container);

Assert.Equal(beforeLoad, afterLoad);
}
}

private static string GetFormattedSum(IFormatProvider fp, decimal money)
{
var fi = fp.GetFormat(typeof(NumberFormatInfo)) as NumberFormatInfo;
return string.Format(fi, "{0:C}", money);
}

private static string GetCodeRegistration(IUnityContainer container)
{
var reg = container.Registrations.Single(r => r.RegisteredType == typeof(IList));
return reg.MappedToType.Name;
}
}
}
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
#if NETCOREAPP
namespace NewPlatform.Flexberry.ORM.ODataService.Tests
{
using System;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Practices.Unity.Configuration;
using Unity;
using Unity.Microsoft.DependencyInjection;

Expand All @@ -26,14 +26,17 @@ public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStar
/// <inheritdoc/>
protected override IWebHostBuilder CreateWebHostBuilder()
{
if (_unityContainer == null)
{
throw new Exception("Unity.IUnityContainer is not defined");
}
// Some tests do not need separate customized containers.
IUnityContainer localContainer = _unityContainer ?? new UnityContainer();
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Стоит добавить комментарий, в каком случае может потребоваться создавать контейнер прямо здесь.

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed

UnityContainerRegistrations.BSProviderRegistration(localContainer);

localContainer.LoadConfiguration();
// Base dependencies registration (Uncomment if you want to use code instead of config for registrations)
UnityContainerRegistrations.Registration(localContainer);

string contentRootDirectory = Directory.GetCurrentDirectory();
var webHostBuilder = new WebHostBuilder()
.UseUnityServiceProvider(_unityContainer)
.UseUnityServiceProvider(localContainer)
.UseContentRoot(contentRootDirectory)
.UseStartup<TestStartup>();
return webHostBuilder;
Expand Down
13 changes: 9 additions & 4 deletions Tests/NewPlatform.Flexberry.ORM.ODataService.Tests/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@ namespace ODataServiceSample.AspNetCore
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.Server.Features;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Practices.Unity.Configuration;
using Moq;
using NewPlatform.Flexberry;
using NewPlatform.Flexberry;
using NewPlatform.Flexberry.ORM.ODataService.Extensions;
using NewPlatform.Flexberry.ORM.ODataService.Files;
using NewPlatform.Flexberry.ORM.ODataService.Model;
Expand All @@ -26,7 +27,7 @@ namespace ODataServiceSample.AspNetCore
using NewPlatform.Flexberry.Services;
using Unity;
using Unity.Injection;
using LockService = NewPlatform.Flexberry.Services.LockService;
using LockService = NewPlatform.Flexberry.Services.LockService;

public class Startup
{
Expand All @@ -49,7 +50,11 @@ public Startup(IConfiguration configuration)
/// <param name="unityContainer">Unity container.</param>
public virtual void ConfigureContainer(IUnityContainer unityContainer)
{
// Configure Flexberry services via Unity.
unityContainer.LoadConfiguration();
// Base dependencies registration. (Uncomment if you want to use code instead of config for registrations)
UnityContainerRegistrations.Registration(unityContainer);

// Configure Flexberry services via Unity.
var securityManager = new EmptySecurityManager();
Mock<IAuditService> mockAuditService = new Mock<IAuditService>();
IBusinessServerProvider businessServerProvider = unityContainer.Resolve<IBusinessServerProvider>();
Expand Down
Loading
Loading