RegisterType with interface in UnityContainer

I am using UnityContainer and I want to register an interface not with a type, but with a different interface. Unfortunately, I cannot do this cleanly.

I have several common interfaces that are combined into one interface, and I need to register them in the container. The code is as follows:

interface IDeviceImporter {
    void ImportFromDevice();
}

interface IFileImporter {
    void ImportFromFile();
}

interface IImporter : IDeviceImporter, IFileImporter {
}


class Importer1: IImporter {
}
class Importer2: IImporter {
}

Upon entering the library, I know which importer to use, so the code looks like this:

var container = new UnityContainer();
if (useFirstImport) {
    container.RegisterType<IImporter, Importer1>();
} else {
    container.RegisterType<IImporter, Importer2>();
}

and then I want to register this particular class using IDeviceImporter and IFileImporter. I need something like:

container.RegisterType<IDeviceImporter, IImporter>();

But with this code, I get an error: IImporter is an interface and cannot be constructed.

I can do this inside the condition, but then it will be copy-paste. I can do

container.RegisterInstance<IDeviceImporter>(container.Resolve<IImporter>());

but he is really dirty. Anyone please advise me something :)

+3
2

ContainerControlledLifetimeManager :

var container = new UnityContainer();
System.Type importerType
if (useFirstImport) {
    importerType = GetType(Importer1);
} else {
    importerType = GetType(Importer2);
}

container.RegisterType(GetType(IImporter), importerType);
container.RegisterType(GetType(IDeviceImporter), importerType);
container.RegisterType(GetType(IFileImporter), importerType);

, - :

container.CreateSymLink<IDeviceImporter, IImporter>()
+1

, . :

  container.RegisterType<IImporter, Importer1>();

, :

var container = new UnityContainer();

if (useFirstImport) {
    container.RegisterType<IImporter, Importer1>();
    container.RegisterType<IDeviceImporter, Importer1>();

} else {
    container.RegisterType<IImporter, Importer2>();
    container.RegisterType<IDeviceImporter, Importer2>();
}

. container.Resolve<IImporter>() , container.Resolve<IDeviceImporter>().

ContainerControlledLifetimeManager, container.RegisterInstance<IDeviceImporter>(container.Resolve<IImporter>()), Unity .

, - container.CreateSymLink<IDeviceImporter, IImporter>(), .

+4

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


All Articles