Unity.AutoRegistration ?? Convention-based unity

My code is as follows

IUnityContainer container = new UnityContainer(); container .ConfigureAutoRegistration() .LoadAssemblyFrom(typeof(Test).Assembly.Location) .LoadAssemblyFrom(typeof(ITest).Assembly.Location) .ApplyAutoRegistration(); 

This is my first question.

I'm not sure if I used the LoadAssemblyFrom method correctly here:

 ITest test = container.Resolve<ITest>(); 

When I try to compile, I get a "ResolutionFailedException" exception.

What am I doing wrong?

Thanks for your time in advance.

+4
source share
2 answers

It looks like you are looking for the following:

 container.ConfigureAutoRegistration() .LoadAssemblyFrom(typeof(ITest).Assembly.Location) .LoadAssemblyFrom(typeof(Test).Assembly.Location) .Include(If.ImplementsITypeName, Then.Register()) .ApplyAutoRegistration(); 

This will inform Unity.AutoRegistration of registration of all types where there is an interface with the same name, with the prefix I.

+4
source

The following is an example of a full working console showing how to install Unity to register by agreement, and then transfer control to the world of dependency injection. To do this, you will need to add the Unity NuGet package.

Tested with Unity v3.5 and VS 2012.

 #region using System; using Microsoft.Practices.Unity; #endregion namespace Demo___Unity { internal class Program { private static void Main(string[] args) { using (var container = new UnityContainer()) { // Manual method. //container.RegisterType<IEntryPoint, EntryPoint>(); //container.RegisterType<IInjected, Injected>(); // Set up registration by convention. // http://blogs.msdn.com/b/agile/archive/2013/03/12/unity-configuration-registration-by-convention.aspx container.RegisterTypes( AllClasses.FromAssembliesInBasePath(), WithMappings.FromMatchingInterface, WithName.Default, WithLifetime.ContainerControlled); var controller = container.Resolve<IEntryPoint>(); controller.Main(); } } } public interface IEntryPoint { string Name { get; set; } void Main(); } public class EntryPoint : IEntryPoint { private readonly IInjected Injected; public EntryPoint(IInjected injected) { Injected = injected; } public void Main() { Console.Write("Hello, world!\n"); Injected.SubMain(); Injected2.SubMain(); Console.Write("[any key to continue]"); Console.ReadKey(); } // Demonstrates property injection. [Dependency] public IInjected Injected2 { get; set; } public string Name { get; set; } } public interface IInjected { void SubMain(); } public class Injected : IInjected { public void SubMain() { Console.Write("Hello, sub world!\n"); } public string Name { get; set; } } } 
+1
source

Source: https://habr.com/ru/post/1486809/


All Articles