Code Monkey home page Code Monkey logo

configuration's People

Contributors

arielszklarkiewicz avatar bennage avatar chavoshi avatar eniks avatar fsimonazzi avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

configuration's Issues

Could not load file or assembly 'Unity.Abstractions, Version=4.1.1.0

I have a dll 'A' which is using Unity(5.10.3) + Unity.Configuration(5.10.0). It has a method which is using following code to load dynamically in container:

var unitySection = (UnityConfigurationSection)configuration.GetSection("Unity");
if (unitySection != null)
	container.LoadConfiguration(unitySection, FullTextContainerName);

Another dll 'B' using only Unity(5.10.3) - again exposing registration method to container.
And a Unit test where I reference both and call their registrations methods.
Once I try to execute this test I receive following exception:
System.IO.FileLoadException: Could not load file or assembly 'Unity.Abstractions, Version=4.1.1.0, Culture=neutral, PublicKeyToken=489b6accfaf20ef0' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

It can be mitigated only if I add to app.config following section:
<runtime> <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1"> <dependentAssembly> <assemblyIdentity name="Unity.Abstractions" publicKeyToken="489b6accfaf20ef0" culture="neutral"/> <bindingRedirect oldVersion="0.0.0.0-4.1.3.0" newVersion="4.1.3.0"/> </dependentAssembly> </assemblyBinding> </runtime>

Is there any other way to do it, or I should go to all application and adapt their configs ?

Method not called on instance creation when registration configured via XML

In XML file method call is configured on type registration. But the method is not called on resolving an instance. Here are samples of configuration and code.
Tested on 5.11.6

  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <reginster type="TestClass">
      <method name="TestMethod" />
    </reginster>
  </unity>
    class Program
    {
        static void Main(string[] args)
        {
            var unity = new UnityContainer();

            var t = unity.Resolve<TestClass>();

            Console.ReadLine();
        }
    }

    public class TestClass
    {
        public TestClass()
        {
            Console.WriteLine("constructor");
        }

        public void TestMethod()
        {
            Console.WriteLine("method");
        }
    }

I run the wpf sample project,when update the nuget package "Unity.Container" and "Unity.Abstractions",something error

update the nuget package "Unity.Container" from 5.8.11 to 5.9.4 and "Unity.Abstractions" from 3.3.1 to 4.0.3,same error happen :
System.IO.FileLoadException
HResult=0x80131040
Message=cannot load “Unity.Abstractions, Version=3.3.1.0, Culture=neutral, PublicKeyToken=6d32ff45e0ccc69f” or it's depends
Source=Prism.Unity.Wpf
StackTrace:
Prism.Unity.PrismApplication.CreateContainerExtension()
Prism.PrismApplicationBase.Initialize()
Prism.PrismApplicationBase.InitializeInternal()
Prism.PrismApplicationBase.OnStartup(StartupEventArgs e)
System.Windows.Application.<.ctor>b__1_0(Object unused)
System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
System.Windows.Threading.DispatcherOperation.InvokeImpl()
System.Windows.Threading.DispatcherOperation.InvokeInSecurityContext(Object state)
System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
MS.Internal.CulturePreservingExecutionContext.Run(CulturePreservingExecutionContext executionContext, ContextCallback callback, Object state)
System.Windows.Threading.DispatcherOperation.Invoke()
System.Windows.Threading.Dispatcher.ProcessQueue()
System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
System.Windows.Application.RunDispatcher(Object ignore)
System.Windows.Application.RunInternal(Window window)
System.Windows.Application.Run(Window window)
System.Windows.Application.Run()
Regions.App.Main() 在 D:\GITRepo\Prism-Samples-Wpf\02-Regions\Regions\obj\Debug\App.g.cs line 57

How to Resolve Generic Class<T>(it's constructor parameter also generic…e.g:Param<T> param) With Unity Container?? help! thanks

interface Interface<T>{}

class Class<T>:Interface<T>
{
      public Class(IInterfaceParam<T> param){}
}

interface IInterfaceParam<T>{}

class InterfaceParam<T>:IInterfaceParam<T>{}

class Tclass{}

 class Program
 {
          void Main(){
                  var v1= container.Resolve<Interface<Tclass>>();
          }
 }

how to config in unity.config xml file?? help! thanks!

bellow is my config:

  <register type="IInterfaceParam`1" mapTo="InterfaceParam`1" name="paramDefault">
  </register>

  <register type="Interface`1" mapTo="Class`1">
    <constructor>
      <param type="IInterfaceParam`1" name="param">
        <dependency name="paramDefault"></dependency>
      </param>
    </constructor>
  </register>

but i got the exception:InvalidOperationException: Configuration is incorrect, the type Class`1 does not have a constructor that takes parameters named param...why???

Unity.Configuration is not built against latest dependencies

The latest version of Unity.configuration available through Nuget is not built against the latest version of it's dependencies.

afbeelding

As a result you have to use assembly binding redirects in order to make use of the new Unity assembly versions. Is there a reason why the Unity.configuration lib is not built against the latest versions of it's dependencies?

Unity.Configuration

The Package Unity.Configuration did not contain any 4.0 lib.
Unity.Configuration 5.0.7

This package is compatible with .NET 4.0, 4.5, and 4.7 frameworks.
=> Dependencies
.NETFramework 4.5
Unity.Abstractions (>= 2.3.0)

.NETFramework 4.7
Unity.Abstractions (>= 2.3.0)

Breaking change

When in config file is defined type with multiple methods - only first is executed. Till version 5.8 everything worked ok, after 5.9 - only first. Same is 5.10 and 5.11.
Example bellow.

class Program
{
    static void Main(string[] args)
    {
        IUnityContainer container = new UnityContainer();
        container.LoadConfiguration();

        var t = container.Resolve<MyClassCollection>();
        Console.WriteLine(t.MyItems.Count);

    }
}

public class MyClassCollection
{
    public IReadOnlyList<IMy> MyItems { get; set; } = new List<IMy>();

    public void Add(IMy pParam)
    {
        ((List<IMy>)MyItems).Add(pParam);
    }
}


public class MyClass : IMy
{

}

public interface IMy
{

}

Config is:

<container>
  <register type="UnityBug.IMy" mapTo="UnityBug.MyClass" name="inst1"/>
  <register type="UnityBug.IMy" mapTo="UnityBug.MyClass" name="inst2"/>
  <register type="UnityBug.IMy" mapTo="UnityBug.MyClass" name="inst3"/>
  <register type="UnityBug.IMy" mapTo="UnityBug.MyClass" name="inst4"/>

  <register type="UnityBug.MyClassCollection">
    <method name="Add">
      <param name="pParam" dependencyName="inst1"/>
    </method>
    <method name="Add">
      <param name="pParam" dependencyName="inst2"/>
    </method>
    <method name="Add">
      <param name="pParam" dependencyName="inst3"/>
    </method>
    <method name="Add">
      <param name="pParam" dependencyName="inst4"/>
    </method>
  </register>
</container>
</unity>

Sample project:
UnityBug.zip

5.9.2 version

Hi, i have Unity.Configuration 5.9.2 version which one depends on Unity.Container 5.9.5 version which one depends on Unity.Abstractions 4.0.3
so Unity.Configuration 5.9.2 -> Unity.Container 5.9.5 -> Unity.Abstractions 4.0.3

Also i have Unity.Abstractions 4.1.0

So that i get runtime error, Unity.Abstractions 4.0.3 cannot be found

One type registered as more different services like autofac

One type registered as more different services is required.
xml configuration of autofac like this:
<components name="Operation"> <type>Autofac.Example.Calculator.Addition.Add, Autofac.Example.Calculator.Addition</type> <services name="Operation" type="Autofac.Example.Calculator.Api.IOperation" /> <services name="AddOperation" type="Autofac.Example.Calculator.Api.IAddOperation" /> </components>

Declaring type's with nested generics by shorthand format in configuration

@atagirov wrote:

When declaring type's with nested generics in shorthand format, nested generics arguments is ignored.

For example:

<register type="IEventBus[IEvent[long], long]" mapTo="EmptyEventBus[IEvent[long], long]" />

first argument IEvent[long] resolved as IEvent`1 instead IEvent[long], because arguments for nested generics is ignored.

Currently, problem resolved by using aliases with .NET type format for arguments:

<alias alias="IEventLong" type="Namespace.IEvent`1[System.Int64], Assembly" />
...
<register type="IEventBus[IEventLong, long]" mapTo="ConsoleEventBus[IEventLong, long]" />

But using "IEventBus[IEvent[long], long]" is more friendly and logical. Also, using alises is hard, when we must declare generics more than second level.

I create a pull-request, they can resolve this, without using aliases - unitycontainer/unity#25

How to load the configuration?

Hi,

this does not work anymore:
new UnityContainer().LoadConfiguration()

Please tell me how to load the configuration.

Upgrade from 5.0.0 to 5.11.1,there's a problem

Upgrade to 5.11.1,Service of OptionalTest.Name is null(required Test)
Work correctly for 5.0.0

<register type="A1" name="TestA1"> <property name="Name" type="string" value="Test"></property> </register>
<register type="OptionalTest" name="OptionalTest"> <property name="Service"> <optional name="TestA1" type="A1" /> </property> </register>
public class A1: A{}
public class OptionalTest { public A Service { get; set; } }

Configuring Liftetime in registration causes object to immediately Dispose

I am migrating from 4.0.1 (this all worked in that version) and have something like this (LogInfo implements Dispose):

 <register type="ILogInfo" mapTo="Foo.LogInfo, Foo.Logging">
      <lifetime type="singleton" />
    </register>

var foo = MainContainer.Resolve<ILogInfo>(); 
MainContainer.RegisterInstance<ILogInfo>(foo);

When I register the instance, Dispose is immediately called on foo.

Now, if I change the registration to:

 <register type="ILogInfo" mapTo="Foo.LogInfo, Foo.Logging">
        </register>

And do this, it works:

var foo = MainContainer.Resolve<ILogInfo>(); 
MainContainer.RegisterInstance<ILogInfo>(foo, new .SingletonLifetimeManager());

Namespace of extension methods

Is there a reason, why multiple extensions (find them here: configuration/src/Extensions) are still in the namespace Microsoft.Practices.Unity.Configuration.ConfigurationHelpers?

If i want to load the unity configuration with the extension container.LoadConfiguration(unitySection);, i still have to include the namespace Microsoft.Practices.Unity.Configuration;.

Is this by intention or just not migrated yet?

Thanks for the help

Unity.Configuration.UnityConfigurationSection is wrong?

I used Unity(5.10.2) and Unity.Configuration(5.10.0) .

I coppied the below setting to my app.config file(.net core2.0 console application) from https://github.com/unitycontainer/configuration/wiki/Format-of-the-Unity-Configuration-File

<section name="unity" type="Unity.Configuration.UnityConfigurationSection, Unity.Configuration"/>

1.I run the console application, and throw below exception at line of var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");

System.Configuration.ConfigurationErrorsException HResult=0x80131902 Message=An error occurred creating the configuration section handler for unity: Could not load type 'Unity.Configuration.UnityConfigurationSection' from assembly 'Unity.Configuration'. (*****bin\Debug\netcoreapp2.0\***.dll.config line 4) Source=System.Configuration.ConfigurationManager StackTrace: at System.Configuration.BaseConfigurationRecord.FindAndEnsureFactoryRecord(String configKey, Boolean& isRootDeclaredHere) at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject) at System.Configuration.BaseConfigurationRecord.GetSection(String configKey) at System.Configuration.ConfigurationManager.GetSection(String sectionName)

2. After I changed the setting to below:
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Unity.Configuration"/>
below code will not throw above exception
var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");

So the setting of "type" in section tag is wrong in
https://github.com/unitycontainer/configuration/wiki/Format-of-the-Unity-Configuration-File
?
Thank you so much!

Problems when when using Unity.Container and Unity.Configuration in .NET 5.0.6 class library via C++\CLI wrapper

I have a solution with the following structure:

  • NET5ClassLibraryInterface - .NET 5.0.6 class library with net5.0-windows TFM. Refefences latest Unity.Container 5.11.11 and Unity.Configuration 5.11.2 nuget packages. Contains IDataCreate interface and a static class that calls functions from that interface (uses container.Resolve<IDataCreate>()). Compiled as x86. Also contains App.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
   <configSections>
      <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Unity.Configuration"/>
   </configSections>

   <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
      <assembly name="NET5ClassLibraryInterface"/>
      <assembly name="NET5ClassLibraryImplementation"/>
      <container>
         <register type="NET5ClassLibraryInterface.IDataCreate" mapTo="NET5ClassLibraryImplementation.DataCreate" />
      </container>
   </unity>
</configuration>
  • NET5ClassLibraryImplementation (references NET5ClassLibraryInterface) - .NET 5.0.6 class library with net5.0-windows TFM - contains DataCreate class that implements IDataCreate interface. Compiled as x86.
  • NET5ClassLibraryTest (references NET5ClassLibraryInterface) - .NET 5.0.6 console application with net5.0-windows TFM - calls functions from NET5ClassLibraryInterface static class. Compiled as x86. Works with no problem!!!.
  • NET5ClassLibraryInterop (references NET5ClassLibraryInterface) - .NET 5.0.6 C++\CLI wrapper. Compiled as x86, Multi-byte Character Set, wchar_t-.
  • NET5ClassLibraryInteropTest - C++ console test application. Compiled as x86, Multi-byte Character Set, wchar_t-.

When I run NET5ClassLibraryInteropTest line var dataGreate = container.Resolve<IDataCreate>(); throws an exception:

System.TypeInitializationException: ''The type initializer for 'NET5ClassLibraryInterface.Class1' threw an exception.'
Inner exception: 'InvalidCastException: Unable to cast object of type 'NET5ClassLibraryImplementation.DataCreate' to type 'NET5ClassLibraryInterface.IDataCreate'.'

I've investigated the problem deeper and found out that if I manually add the following line to NET5ClassLibraryInterop.vcxproj:

<ItemGroup>
    <FrameworkReference Include="Microsoft.WindowsDesktop.App.WindowsForms" />
</ItemGroup>

the problem transforms. Line var section = c.GetSection("unity") as UnityConfigurationSection now returns section = null despite of the fact that c.GetSection("unity") is exactly {Microsoft.Practices.Unity.Configuration.UnityConfigurationSection}:
image
image

Sample repo -https://github.com/bairog/NET5ClassLibraryWithUnityInteropTest
Compile it (for some reason you need to compile twice for compiling NET5ClassLibraryInteropTest project) and start debugging NET5ClassLibraryInterop project (it starts NET5ClassLibraryInteropTest in project Debug settings)

Version information

Target framework: .NET 5.0.6
Operating system: Windows 10 x64 1909
IDE: Visual Studio 2019 16.10.0 REL Community

Error in Generic class with Ienumerable generic parameter

Description

I have an error when I use the unity.configuration that I can't reproduce without the configuration,
I have Interfaces IRepository and IRule
and the Repository class receives an IEnumerable<IRule in the constructor

If I use the unity.config file to register those registrations, I get an error in the resolve of the IRepository.
But if I register by code, I can't reproduce the error, I think that something is missing in the registration, but I can't find what it is.

To Reproduce

Please provide UnitTest in the form of:

class ErrorGenericAndConfig
	{
		[TestMethod]
		static void ErrorWithGenericIEnumerableAndUnityConfig()
		{
			var container = new UnityContainer();

			var unitySection = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
			if (unitySection != null)
			{
				unitySection.Configure(container);

			}
			var rep = container.Resolve<IRepository<Entity>>();

			AssertExtensions.IsInstanceOfType(rep, typeof(Repository<Entity>));

			var container2 = new UnityContainer();
			container2.RegisterType(typeof(IRepository<>), typeof(Repository<>),new HierarchicalLifetimeManager());
			container2.RegisterType(typeof(IRule<>), typeof(Rule1<>), "Rule1", new HierarchicalLifetimeManager(),new Unity.Registration.InjectionMember[] { });
			container2.RegisterType(typeof(IRule<>), typeof(Rule2<>), "Rule2", new HierarchicalLifetimeManager(), new Unity.Registration.InjectionMember[] { });
			var rep2 = container2.Resolve<IRepository<Entity>>();

			AssertExtensions.IsInstanceOfType(rep2, typeof(Repository<Entity>));


		}
	}

	public interface IRepository<T>
	{
	}

	public class Repository<T> : IRepository<T>
	{
		public Repository(IEnumerable<IRule<T>> rules)
		{
			this.Rules = rules;
		}

		public IEnumerable<IRule<T>> Rules { get; }
	}

	public interface IRule<T>
	{

	}
	public class Rule2<T> : IRule<T>
	{

	}
	public class Rule1<T> : IRule<T>
	{

	}

	public class Entity
	{
		public int Id { get; set; }
		public string Description { get; set; }
	}

Additional context

<unity xmlns="http://schemas.microsoft.com/practices/2010/unity"> <container> <register type="ErroUnityGeneric.IRepository1, ErroUnityGeneric"
mapTo="ErroUnityGeneric.Repository`1, ErroUnityGeneric"
name="">




	<register type="ErroUnityGeneric.IRule`1, ErroUnityGeneric"
					mapTo="ErroUnityGeneric.Rule1`1, ErroUnityGeneric"
					name="Rule1">
		<lifetime  type="hierarchical"/>
		<constructor >
		</constructor>
	</register>
	<register type="ErroUnityGeneric.IRule`1, ErroUnityGeneric"
					mapTo="ErroUnityGeneric.Rule2`1, ErroUnityGeneric"
					name="Rule2">
		<lifetime  type="hierarchical"/>
		<constructor >
		</constructor>
	</register>

</container>

`

Could not load type 'Unity.UnityContainerExtensions' from assembly 'Unity.Container, Version=5.9.2.0,....

Hello

I get an exception when configuring an extension from the config. Any ideas ??

var section = (UnityConfigurationSection)configuration.GetSection("unity");
section.Configure(container);

Exception:
System.TypeLoadException
Could not load type 'Unity.UnityContainerExtensions' from assembly 'Unity.Container, Version=5.9.2.0, Culture=neutral, PublicKeyToken=489b6accfaf20ef0'.
at Microsoft.Practices.Unity.Configuration.ContainerExtensionElement.ConfigureContainer(IUnityContainer container)
at Microsoft.Practices.Unity.Configuration.ContainerElement.ConfigureContainer(IUnityContainer container)
at Microsoft.Practices.Unity.Configuration.UnityConfigurationSection.Configure(IUnityContainer container, String configuredContainerName)

net core

Could you please provide an information on release unitycontainer/configuration under core 2.0?
Do you have any plans to port it?
If so, could you provide the estimated release date?

Multiple method elements no more supported under register?

Description

The support for unbounded number of method elements under the register node seems to have been removed. Now only the first method call is made. The schema for InjectionGroup defines "method" to be: minOccurs="0" maxOccurs="unbounded".

I'm not sure where it got lost but we are upgrading from old 4 to latest.

To Reproduce

    public interface IChild
    {
        int Age { get; set; }
    }

    public interface IParent
    {
        IList<IChild> Children { get; set; }
        void Add(IChild child);
    }

    public class Child : IChild
    {
        public int Age { get; set; }

        public Child(int age)
        {
            Age = age;
        }
    }

    public class Parent : IParent
    {
        public IList<IChild> Children { get; set; }

        public Parent()
        {
            Children = new List<IChild>();
        }

        public void Add(IChild child)
        {
            Children.Add(child);
        }
    }

    [TestClass]
    public class Test
    {
        [TestMethod]
        public void ResolveInstanceWithMultipleMethodCallsTest()
        {
            // Arrange
            var container = new UnityContainer();
            container.LoadConfiguration();

            // Act
            var parent = container.Resolve<IParent>();

            // Assert
            Assert.AreEqual(2, parent.Children.Count);
        }
    }

Additional context

The above test used this configuration:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Unity.Configuration" />
  </configSections>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
  </startup>

  <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
    <namespace name="UnityTest" />
    <assembly name="UnityTest" />
    <container>
      <register type="IParent" mapTo="Parent">
        <method name="Add">
          <param name="child" dependencyName="Child1" />
        </method>
        <method name="Add">
          <param name="child" dependencyName="Child2" />
        </method>
      </register>
      <register name="Child1" type="IChild" mapTo="Child">
        <constructor>
          <param name="age" value="12" />
        </constructor>
      </register>
      <register name="Child2" type="IChild" mapTo="Child">
        <constructor>
          <param name="age" value="6" />
        </constructor>
      </register>
    </container>
  </unity>
</configuration>

Resolving 2 Objects of same type but different version

Description

We have a scenario where we can registry in config file 2 Singleton of the same type but different dll version. In the background we have 2dll classes (Only different version) which all implement the desired interface. We would like to use Unity to resolve 2 instances for this interface.

To Reproduce

  1. Create config file
  <unity>
    <aliases>
      <add alias="DtmParameter1" type="FullFrameworkLibLogic.DtmParameter,  FullFrameworkLibLogic, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null" />
      <add alias="DtmParameter2" type="FullFrameworkLibLogic.DtmParameter, FullFrameworkLibLogic, Version=5.5.5.5, Culture=neutral, PublicKeyToken=null" />
      <add alias="my" type="FullFrameworkLibLogic.DtmParameter, FullFrameworkLibLogic" />

      
    </aliases>
    <container>

      <register name="1" type="IDtmParameter" mapTo="DtmParameter1">
<lifetime type="singleton" />
      </register>

      <register name="2" type="IDtmParameter" mapTo="DtmParameter2">
        <lifetime type="singleton" />
      </register>
    </container>
  </unity>
</configuration>
  1. Test like this

[TestMethod]
public void SomeDescriptiveName()
{
        IDtmParameter dtmParameter1 = this.container.Resolve<IDtmParameter>("1");
            var msg1 = dtmParameter1.GetVersion();
            Console.WriteLine(msg1);

            IDtmParameter dtmParameter2 = this.container.Resolve<IDtmParameter>("2");
            var msg2 = dtmParameter2.GetVersion();
            Console.WriteLine(msg2);
}

image

Cannot setup Unity Container 5 (an issue with Unity.Configuration 5.11.1)

I'm trying to setup a simple .NET Core 3.1 project that uses Unity Container 5 (https://github.com/unitycontainer/unity)

I've added a reference to latest Unity Configuration 5.11.1 package (https://www.nuget.org/packages/Unity.Configuration/).

Then I've created interface, implementation and test app with a simpliest config file:

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
      <configSections>
        <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Unity.Configuration" />
      </configSections>
      <unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
        <container>
          <register
            type="Interfaces.InterfaceN, Interfaces"
            mapTo="Implementations.ImplementationN, Implementations">
          </register>
        </container>
      </unity>
    </configuration>

But i'm getting System.InvalidOperationException:

{"The type name or alias Implementations.ImplementationN,
Implementations could not be resolved. Please check your configuration
file and verify this type name."}

I've uploaded my code to GitHub.

Same code compiled for .NET Framework 4.8 works fine - GitHub

Any help is appreciated.

Could not load file or assembly 'Unity.Abstractions, Version=5.11.2.0'

I have a dll 'A' which is using latest Unity.Container(5.11.11.0), Unity.Abstractions(5.11.7.0) and Unity.Configuration(5.11.2.0). It has a method which is using following code to load dynamically in container (that container is exposed):

container = new UnityContainer();
var unitySection = configuration.Sections["unity"] as UnityConfigurationSection;
container.LoadConfiguration(unitySection);

Another dll 'B' using only Unity.Container(5.11.11.0), Unity.Abstractions(5.11.7.0) and performs class creations (and it uses dll 'A'):
IMyInterface class = container.Resolve<IMyInterface>();

Once I try to execute a test application (that uses dll 'B') I receive following exception:

System.IO.FileLoadException: Could not load file or assembly 'Unity.Abstractions, Version=5.11.2.0, Culture=neutral, PublicKeyToken=489b6accfaf20ef0' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

Very strange, because I compile both libraries with Unity.Abstractions(5.11.7.0).
As a workaround I'm using AppDomain.CurrentDomain.AssemblyResolve event and load appropriate library directly.

But what is the root of this problem? Howto get rid of it?

P. S. I use Visual Studio 2019 16.9.0 and my modules are compied for .NET Framework 4.0.

Can be related to #20

It does not support .netcore2.2?

In order to create a new class instance by config file. I use Unity.configuration. and Unity(5.10.2).

I used the latest version of "5.10.0" in .net core 2.2 console application. It threw exception for the following code:

using (var container = new UnityContainer()) { UnityConfigurationSection section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity"); section.Configure(container, "Default");// threw exception in this line }

Below the exception:
System.InvalidOperationException HResult=0x80131509 Message=The type name or alias **** could not be resolved.Please check your configuration file and verify this type name. Source=Unity.Configuration StackTrace: at Microsoft.Practices.Unity.Configuration.ConfigurationHelpers.TypeResolverImpl.ResolveType(String typeNameOrAlias, Boolean throwIfResolveFails) at Microsoft.Practices.Unity.Configuration.RegisterElement.ConfigureContainer(IUnityContainer container) at Microsoft.Practices.Unity.Configuration.ContainerElement.ConfigureContainer(IUnityContainer container) at Microsoft.Practices.Unity.Configuration.UnityConfigurationSection.Configure(IUnityContainer container, String configuredContainerName)
The same code work fine in .net 4.6.

does it not support .netcore2.2? May I know when will release the new version which support .netcore 2.2?

thank you so much

@ENikS

It doesn't support .netcore 2.0?

it support .netcore2.0 in the guget below:
https://www.nuget.org/packages/Unity.Configuration/

I did a testing for .netcore 2.0 console application and found that it did not work. below is the details:

1.app.config:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <configSections> <section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Unity.Configuration"/> </configSections> <unity xmlns="http://schemas.microsoft.com/practices/2010/unity"> <alias alias="Ilogging" type="Will.Framework.Abstract.Logging.Ilogging, Will.Framework.Abstract" /> <container> <register type="Ilogging" mapTo="Will.Logging.Win.ClsILogging, Will.Logging.Win" /> </container> </unity> </configuration>

  1. below is the function in class "Program"
  private static void LoadDllTest()
        {
            using (var container = new UnityContainer())
            {
                var section = (UnityConfigurationSection)ConfigurationManager.GetSection("unity");
                section.Configure(container);
                var LoggingWeb = container.Resolve();        
            }
        }

3.Below is the exception from line of " section.Configure(container);":

   at Microsoft.Practices.Unity.Configuration.ConfigurationHelpers.TypeResolverImpl.ResolveType(String typeNameOrAlias, Boolean throwIfResolveFails) in C:\projects\configuration\src\ConfigurationHelpers\TypeResolverImpl.cs:line 103
   at Microsoft.Practices.Unity.Configuration.RegisterElement.ConfigureContainer(IUnityContainer container)
   at Microsoft.Practices.Unity.Configuration.ContainerElement.ConfigureContainer(IUnityContainer container) in C:\projects\configuration\src\Elements\ContainerElement.cs:line 101
   at Microsoft.Practices.Unity.Configuration.UnityConfigurationSection.Configure(IUnityContainer container, String configuredContainerName) in C:\projects\configuration\src\Section\UnityConfigurationSection.cs:line 141

4.If I added the reference of "Will.Logging.Win" the function LoadDllTest will work. But for this situation, the unity container doesn't make any sense yet. and I can just create the instance directly.

Any suggestion is appreciated!

Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.