Как использовать DI с Unity после динамической регистрации DLL - PullRequest
0 голосов
/ 23 января 2020

Я регистрирую свои Dlls динамически с Unity

public static void RegisterTypes(IUnityContainer container)
{
    string dependenciesPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "SpecificDll");
    string[] dependencies = Directory.GetFiles(dependenciesPath);
    Dictionary<Type, Type> pluginMappings = new Dictionary<Type, Type>();
    //Load Dependency Assemblies
    foreach (string fileName in dependencies)
    {
        //Get type interface and plugin type
        ....
    }
    foreach (var mapping in pluginMappings)
    {
        container.RegisterType(mapping.Key, mapping.Value);
    }
}

Я использовал, чтобы зарегистрировать свой класс таким образом

container.RegisterType<IService, Service>(new HierarchicalLifetimeManager());

И использовать его таким образом

public class MyController : ApiController
{
    private Service _service;
    public MyController(Service service)
    {
        _service = service;
    }
}

Но я не знаю, как это сделать, когда я загружаю сборки динамически.

Вы можете мне помочь?

Thx

1 Ответ

0 голосов
/ 24 января 2020

Наконец, я создал третий проект с общими интерфейсами.

В моем Dll:

    public class ServiceSpe : IServiceSpe
    {
        public string GetLabel()
        {
            return "hello world";
        }
    }

В моем общем проекте:

    public interface IServiceSpe
    {
        string GetLabel();
    }

В моем контроллере :

    public MyController()
    {
    }

    public MyController(IServiceSpe serviceSpe)
    {
        if (serviceSpe != null)
        {
            string result = serviceSpe.GetLabel();
        }
    }

Если зависимость содержит класс с интерфейсом "IServiceSpe":

MyController (IServiceSpe serviceSpe) вызывается

else

MyController () is называется

...