Unity IoC for resolving assemblies dynamically

前端 未结 2 736
灰色年华
灰色年华 2020-12-30 16:55

We are using unity as IoC. We came across unique problem. We have created interface called IPlugin. This interface is shared across various third party vendors to develop th

相关标签:
2条回答
  • 2020-12-30 17:36

    You could write a bit of Reflection code that scans a folder for add-in assemblies and registers all IPlugin implementations with the container.

    Something like this ought to work:

    var assemblies = // read all assemblies from disk
    var pluginTypes = from a in assemblies
                      from t in a.GetExportedTypes()
                      where typeof(IPlugin).IsAssignableFrom(t)
                      select t;
    
    foreach (var t in pluginTypes)
        container.RegisterType(typeof(IPlugin), t);
    

    (code may not compile)

    0 讨论(0)
  • 2020-12-30 17:46
        var assemblies = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory, "Worker*.dll").Select(f => Assembly.LoadFile(f)).ToArray<Assembly>();
    
        (from asm in assemblies
            from t in asm.GetExportedTypes()
            where typeof(ICommonWorker).IsAssignableFrom(t) && t.IsClass
            select t).ForEach(x =>
        {
            unityContainer.RegisterType(typeof(ICommonWorker), x, x.FullName, new ContainerControlledLifetimeManager());
        });
    

    If anyone still cares, this is what I did to load DLL's dynamically which implemented a specific interface (ICommonWorker).

    0 讨论(0)
提交回复
热议问题